ggplot2绘图点的形状不够用怎么办?
群里有這么一個問題:
請問老師,fviz_pca_ind 做pca,當設置geom.ind = “point”,group>6時,就不能顯示第7,8組的點,應該如何處理(在不設置為文本的情況下),只改變點的幾何形狀和顏色
fviz_pca_ind是factoextra里面用來可視化PCA結果的一個參數,具體見PCA主成分分析實戰和可視化 | 附R代碼和測試數據。
這個問題是ggplot2繪制形狀時的通用問題,默認只支持6種形狀。我們生成個測試數據看下效果:
x <- 1:50 y <- dpois(x, lambda = 10) data <- data.frame(X=x,y=y) data$type <- as.factor(x) library(ggplot2)ggplot(data, aes(x=x, y=y)) + geom_point(aes(shape=type))圖效果如下。同時給出了一段提示:
Warning: The shape palette can deal with a maximum of 6 discrete values because more than 6 becomes difficult to discriminate; you have 50. Consider specifying shapes manually if you must have them.
Warning: Removed 44 rows containing missing values (geom_point).
就是說我們需要自己手動指定形狀。
ggplot2默認支持下面122種形狀。
# 代碼來自 http://sape.inf.usi.ch/quick-reference/ggplot2/shape d=data.frame(p=c(0:25,32:127)) ggplot() + scale_y_continuous(name="") + scale_x_continuous(name="") + scale_shape_identity() + geom_point(data=d, mapping=aes(x=p%%16, y=p%/%16, shape=p), size=5, fill="red") +geom_text(data=d, mapping=aes(x=p%%16, y=p%/%16+0.25, label=p), size=3)那怎么利用起來呢?需要轉換計算下能用的符號編號,這里選取0:14, 33-127 ?(15-25是其它形狀加了顏色或變了大小,可能會對設置的大小或顏色屬性有影響,先暫時忽略了; 32沒看出來是什么形狀)。
下面根據設定的符號列的因子數,通過取余數的方式獲取這些數字,然后傳遞給scale_shape_manual函數。
shape_level <- nlevels(data[["type"]]) if (shape_level < 15){shapes = (0:shape_level) %% 15 } else{shapes = c(0:14,c((15:shape_level) %% 110 + 18)) }ggplot(data, aes(x=x, y=y)) + geom_point(aes(shape=type)) + scale_shape_manual(values=shapes)回到上面的問題,因為沒有給代碼和數據,這里也就只能意思一下了。
# type 需要改成自己映射到形狀的列名 shape_level <- length(levels(data[["type"]])) if (shape_level < 15){shapes = (0:shape_level) %% 15 } else{shapes = c(0:14,c((15:shape_level) %% 110 + 18)) }fviz_pca_ind(....) + scale_shape_manual(values=shapes)往期精品(點擊圖片直達文字對應教程)
機器學習
后臺回復“生信寶典福利第一波”或點擊閱讀原文獲取教程合集
總結
以上是生活随笔為你收集整理的ggplot2绘图点的形状不够用怎么办?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用C来扩展python功能。
- 下一篇: 用C语言扩展Python的功能的实例