如何在ggplot中按POP分组为geom_bar()条形设置分组边框而非按ID个体设置
实现方案
要实现按POP分组设置条形外边框颜色,可通过新增一层无填充、仅映射边框颜色到POP的条形图层实现,避免堆叠的每个ancestry块都出现边框,具体修改如下:
- 预处理数据,将IND按POP排序,保证同POP的个体连续排列,边框展示更整齐:
# 预处理:将IND按POP排序,设置因子水平保证绘图时同POP个体相邻 long_form_combined <- long_form_combined[order(long_form_combined$POP), ] long_form_combined$IND <- factor(long_form_combined$IND, levels = unique(long_form_combined$IND)) # 计算每个IND的总value,用于绘制整根条形的外边框 ind_total <- aggregate(value ~ IND + POP, data = long_form_combined, FUN = sum)
- 修改后的ggplot代码:
ggplot(long_form_combined, aes(x=IND, y=value, fill=ancestry)) + # 原堆叠条形层,不设置边框,避免每个ancestry块都显示边框 geom_bar(position=position_stack(), stat="identity", width=1) + # 新增外边框层:仅绘制整根条形的边框,映射color到POP实现按组设置边框 geom_bar(data = ind_total, aes(x=IND, y=value, color=POP), stat="identity", fill=NA, width=1, linewidth=0.5) + ylim(c(-1.2, 1.2)) + scale_fill_manual(values=c("ancestry1"="RoyalBlue", "ancestry2"="ForestGreen", "ancestry3"="gold", "ancestry4"="indianred1", "ancestry5"="olivedrab1", "ancestry6"="springgreen", "ancestry7"="sienna", "ancestry8"="skyblue")) + # 可自定义POP对应的边框颜色,不需要自定义可删除本行 scale_color_manual(values = c("Kharia"="红色对应色值", "Papuan"="蓝色对应色值")) + coord_polar(start = -1) + theme(axis.text.x = element_blank(), axis.title.x = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), legend.title=element_blank())
- 参数说明:
linewidth可以调整边框粗细,根据展示需求自行调整即可- 提前对IND按POP排序可以保证同组个体连续排列,边框视觉上更统一
内容的提问来源于stack exchange,提问作者Lindo
相关产品推荐
相关产品推荐

