如何去除R中使用ggplot2建立的圖表中點與座標軸之間的額外邊距?
在使用ggplot包建立的圖表中,圖表四周存在額外的區域,佔用額外的空間,因此我們可能希望透過去除該額外邊距區域來消除該空間。這可以透過使用`scale_x_continuous`和`scale_y_continuous`函式將兩個座標軸的比例設定為零來實現。
考慮以下資料框:
示例
set.seed(151) x<-rnorm(20,5,1) y<-rnorm(20,5,2) df<-data.frame(x,y) df
輸出
x y 1 4.948461 2.255857 2 5.765737 1.726474 3 4.853260 4.280697 4 4.886814 7.402230 5 4.604489 3.708252 6 5.782276 3.978782 7 3.602522 3.801754 8 3.981162 6.091206 9 5.229476 4.017412 10 5.672173 5.383071 11 4.515448 3.882945 12 5.560609 6.845399 13 5.066156 7.307996 14 3.650124 2.255179 15 4.757084 7.580363 16 3.763259 7.309804 17 3.525322 7.891359 18 7.437159 5.522026 19 5.673526 8.858292 20 5.310040 3.800228
載入ggplot2包並在x和y之間建立散點圖:
示例
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
輸出
透過排除額外邊距區域在x和y之間建立散點圖:
示例
ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(expand=c(0,0))+scale_y_continuous(expand=c(0,0))
輸出
廣告