前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2绘图点的形状不够用怎么办?

ggplot2绘图点的形状不够用怎么办?

作者头像
生信宝典
发布2022-01-18 20:59:47
1.5K1
发布2022-01-18 20:59:47
举报
文章被收录于专栏:生信宝典生信宝典

群里有这么一个问题:

请问老师,fviz_pca_ind 做pca,当设置geom.ind = “point”,group>6时,就不能显示第7,8组的点,应该如何处理(在不设置为文本的情况下),只改变点的几何形状和颜色

fviz_pca_indfactoextra里面用来可视化PCA结果的一个参数,具体见PCA主成分分析实战和可视化 | 附R代码和测试数据

这个问题是ggplot2绘制形状时的通用问题,默认只支持6种形状。我们生成个测试数据看下效果:

代码语言:javascript
复制
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种形状。

代码语言:javascript
复制
# 代码来自 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函数。

代码语言:javascript
复制
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)

回到上面的问题,因为没有给代码和数据,这里也就只能意思一下了。

代码语言:javascript
复制
# 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)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-08-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 生信宝典 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档