如何提取R中使用ggplot2繪製的圖表的座標軸標籤?


當我們使用ggplot2建立圖表時,兩個座標軸的座標軸標籤會自動生成。我們可能希望將這些座標軸標籤用於報告撰寫或其他用途,因此,可以使用ggplot_build函式提取使用ggplot2包建立的圖表的這些標籤,如下例所示,但我們需要將圖表儲存在一個物件中。

考慮以下資料框:

示例

 線上演示

x<-rnorm(20)
y<-rnorm(20,5,0.32)
df<-data.frame(x,y)
df

輸出

        x          y
1  -0.48260000   5.306990
2   1.46738002   5.065480
3  -0.41960276   4.833763
4   1.13728029   4.927692
5  -0.58233296   4.789553
6  -1.33506461   4.752065
7  -0.15042591   4.672583
8  -0.14903138   4.671353
9   1.00647384   5.090690
10 -0.18414152   4.815529
11 -2.20077514   4.353975
12  1.00566656   5.050006
13  0.14784372   5.067741
14  1.35535140   4.858750
15 -0.59944199   5.457906
16 -0.95290747   4.994523
17 -2.12832109   5.348286
18 -1.63202006   5.100371
19  0.07918045   4.869089
20 -1.23168746   4.617075

載入ggplot2包並在x和y之間建立散點圖:

示例

library(ggplot2)
p<-ggplot(df,aes(x,y))+geom_point()
p

輸出

ggplot_build(p)$layout$panel_params[[1]]$y$get_labels()

[1] NA "4.50" "4.75" "5.00" "5.25" "5.50"

ggplot_build(p)$layout$panel_params[[1]]$x$get_labels()

[1] "-2" "-1" "0" "1" NA

更新於:2021年2月8日

444 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告