在ggplot2分组叠加图中设置不同形状类型的实现方法
在ggplot2中分别设置抖动点与均值点的形状类型
当然可以实现你的需求,核心是绕过全局形状映射的限制,给不同图层单独指定形状规则。以下是两种可行方案:
方案一:无需额外包,手动指定形状数值
直接在每个图层的aes()中根据分组变量分配空心/实心形状,再调整图例统一显示:
library(ggplot2) # 获取seeding.rate的实际水平(替换为你的数据真实值) seed_levels <- levels(econ4$seeding.rate) p <- ggplot() + # 抖动观测点:空心形状分组 geom_jitter(data = econ4, position = position_jitter(0.2), aes(x = location, y = profit, shape = ifelse(seeding.rate == seed_levels[1], 1, 2), # 1=空心圆,2=空心三角 colour = urea.cost.USD), alpha = 0.05) + # alpha放在aes外,避免多余图例 theme_bw() + geom_hline(yintercept = 0) + labs(y = "profit per ha (USD)", shape = "seeding.rate") + # 均值点:实心形状分组 geom_point(data = econ4, aes(x = location, y = mean.profit, colour = urea.cost.USD, shape = ifelse(seeding.rate == seed_levels[1], 16, 17)), #16=实心圆,17=实心三角 size = 2) + # 增大均值点,强化视觉区分 geom_linerange(data = econ4, aes(x = location, y = mean.profit, ymin = mean.profit - se.profit, ymax = mean.profit + se.profit, colour = urea.cost.USD)) + scale_colour_manual(values = c("#0072B2","#009E73", "#CC79A7")) + coord_flip() + # 调整图例:合并空心/实心对应的同一分组 scale_shape_manual(values = c(1, 2, 16, 17), labels = c(seed_levels[1], seed_levels[2], seed_levels[1], seed_levels[2]), guide = guide_legend( override.aes = list(shape = c(1, 16)), label = seed_levels, ncol = 1 )) p
方案二:使用ggnewscale包(更简洁)
ggnewscale允许为同一美学属性设置多个映射规则,代码结构更清晰:
library(ggplot2) library(ggnewscale) # 需要先安装:install.packages("ggnewscale") p <- ggplot() + # 抖动点:空心形状映射 geom_jitter(data = econ4, position = position_jitter(0.2), aes(x = location, y = profit, shape = seeding.rate, colour = urea.cost.USD), alpha = 0.05) + scale_shape_manual(name = "seeding.rate", values = c(1, 2)) + # 空心形状 scale_colour_manual(values = c("#0072B2","#009E73", "#CC79A7")) + new_scale("shape") + # 开启新的shape映射规则 # 均值点:实心形状映射 geom_point(data = econ4, aes(x = location, y = mean.profit, shape = seeding.rate, colour = urea.cost.USD), size = 2) + scale_shape_manual(name = "seeding.rate", values = c(16, 17)) + # 实心形状 # 其他图层 geom_linerange(data = econ4, aes(x = location, y = mean.profit, ymin = mean.profit-se.profit, ymax = mean.profit+se.profit, colour = urea.cost.USD)) + theme_bw() + geom_hline(yintercept = 0) + labs(y = "profit per ha (USD)") + coord_flip() p
关键注意事项
- 不要把
alpha=0.05放在aes()内部,否则会生成多余的透明度图例。 - 给均值点设置
size=2可以和抖动点形成明显视觉区分,提升图表可读性。
内容的提问来源于stack exchange,提问作者LKK
相关产品推荐
相关产品推荐

