如何有條件地在 R 中更改 geom_point 中的點大小?
要根據條件更改 geom_point 中的點大小,我們可以在 geom_point 中使用 aes 定義條件,並使用 ggplot2 包的 scale_size_manual 函式定義大小。例如,如果我們有一個稱為 df 的資料框,其中包含兩列,比如 x 和 y,則可以用以下命令繪製 x 值大於 5 且小於等於 5 的點大小不同的散點圖:-
ggplot(df,aes(x,y))+geom_point(aes(size=x>5))+scale_size_manual(values=c(4,7))
示例
考慮以下資料框 -
x<-rnorm(20,6,1.2) y<-rnorm(20,10,0.3) df<-data.frame(x,y) df
輸出
x y 1 3.328193 10.220022 2 5.230092 9.947973 3 7.870149 9.385716 4 7.250473 10.312204 5 7.859332 9.628415 6 6.344924 9.389630 7 5.950067 9.927424 8 3.598442 10.078970 9 5.243530 9.545237 10 5.546215 10.153369 11 8.037851 9.903173 12 7.607763 10.354359 13 6.264471 10.029382 14 5.604859 10.421269 15 6.053001 9.621305 16 6.778453 9.819948 17 5.570402 9.931298 18 5.046742 10.003627 19 6.783095 9.783940 20 4.774991 10.502797
載入 ggplot2 包並在 x 和 y 之間建立一個散點圖 -
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
輸出
為 x 值大於 6 且小於等於 6 的散點圖在 x 和 y 之間建立不同點大小 -
示例
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(3,10))
輸出
示例
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(2,6))
輸出
示例
ggplot(df,aes(x,y))+geom_point(aes(size=x>6))+scale_size_manual(values=c(4,7))
輸出
廣告