ggplot2绘图点的形状不够用怎么办?
群里有這么一個(gè)問題:
請(qǐng)問老師,fviz_pca_ind 做pca,當(dāng)設(shè)置geom.ind = “point”,group>6時(shí),就不能顯示第7,8組的點(diǎn),應(yīng)該如何處理(在不設(shè)置為文本的情況下),只改變點(diǎn)的幾何形狀和顏色
fviz_pca_ind是factoextra里面用來可視化PCA結(jié)果的一個(gè)參數(shù),具體見PCA主成分分析實(shí)戰(zhàn)和可視化 | 附R代碼和測(cè)試數(shù)據(jù)。
這個(gè)問題是ggplot2繪制形狀時(shí)的通用問題,默認(rèn)只支持6種形狀。我們生成個(gè)測(cè)試數(shù)據(jù)看下效果:
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))圖效果如下。同時(shí)給出了一段提示:
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).
就是說我們需要自己手動(dòng)指定形狀。
ggplot2默認(rèn)支持下面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)那怎么利用起來呢?需要轉(zhuǎn)換計(jì)算下能用的符號(hào)編號(hào),這里選取0:14, 33-127 ?(15-25是其它形狀加了顏色或變了大小,可能會(huì)對(duì)設(shè)置的大小或顏色屬性有影響,先暫時(shí)忽略了; 32沒看出來是什么形狀)。
下面根據(jù)設(shè)定的符號(hào)列的因子數(shù),通過取余數(shù)的方式獲取這些數(shù)字,然后傳遞給scale_shape_manual函數(shù)。
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)回到上面的問題,因?yàn)闆]有給代碼和數(shù)據(jù),這里也就只能意思一下了。
# 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)往期精品(點(diǎn)擊圖片直達(dá)文字對(duì)應(yīng)教程)
機(jī)器學(xué)習(xí)
后臺(tái)回復(fù)“生信寶典福利第一波”或點(diǎn)擊閱讀原文獲取教程合集
總結(jié)
以上是生活随笔為你收集整理的ggplot2绘图点的形状不够用怎么办?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用C来扩展python功能。
- 下一篇: 用C语言扩展Python的功能的实例