如何用ggplot绘制Genotype同色、仅显示Season图例的分组柱状图?
解决方案:按基因型统一填充色,用线条/图案区分季节且仅显示季节图例
你的核心需求是保持每个基因型(Genotype)柱子填充色一致,通过线条样式或填充图案区分不同季节(Season),同时只保留季节的图例。以下是两种实现方式:
方式一:用线条样式(linetype)区分季节
无需额外安装包,直接使用ggplot原生功能即可实现:
# 加载ggplot2 library(ggplot2) # 你的数据集 Genotype=c("A","A","B","B","C","C","A","A","B","B","C","C") Season=c("2022","2023","2022","2023","2022","2023","2022","2023","2022","2023","2022","2023") Type=c("I","I","I","I","I","I","II","II","II","II","II","II") Yield=c(100,120,110,80,60,90,100,100,170,80,30,90) dataA= data.frame(Genotype, Season, Type, Yield) # 绘图代码 ggplot(data=dataA, aes(x=Genotype, y=Yield, fill=Genotype, group=interaction(Genotype, Season), # 确保同基因型下分季节错开 color=Season, linetype=Season))+ # 用线型区分季节 geom_bar(stat="identity", position="dodge", width=0.7, size=1) + scale_fill_manual(values=c("darkred","blue","grey")) + # 基因型填充色保持设定 scale_color_manual(values=c("black","orange")) + # 季节对应的边框颜色 scale_linetype_manual(values=c("solid", "dashed")) + # 季节对应的线型 labs(x="Genotype", y="Yield") + theme_classic(base_size=18, base_family="serif") + theme(legend.position="right", legend.title=element_blank(), legend.key=element_rect(color="white", fill="white"), legend.text=element_text(family="serif", face="plain", size=15, color="black"), legend.background= element_rect(fill="white"), axis.line = element_line(linewidth = 0.5, colour="black"))+ guides(fill="none") # 隐藏基因型的填充图例,仅保留季节图例
关键调整说明:
- 在
aes中添加linetype=Season,将季节映射为不同线型 - 设置
group=interaction(Genotype, Season),确保同一基因型下的不同季节柱子能正确错开排列 - 通过
guides(fill="none")隐藏基因型的填充图例,只保留季节相关的线型+颜色图例
方式二:用填充图案区分季节(需安装ggpattern包)
如果想用填充图案替代线型,可使用ggpattern扩展包,图案区分会更直观:
# 先安装并加载ggpattern # install.packages("ggpattern") library(ggpattern) library(ggplot2) # 绘图代码 ggplot(data=dataA, aes(x=Genotype, y=Yield, fill=Genotype, group=interaction(Genotype, Season), pattern=Season))+ # 用图案区分季节 geom_bar_pattern(stat="identity", position="dodge", width=0.7, pattern_fill="black", # 图案颜色 pattern_density=0.1, # 图案密度 pattern_spacing=0.05, # 图案间距 color="black") + # 柱子边框统一黑色 scale_fill_manual(values=c("darkred","blue","grey")) + scale_pattern_manual(values=c("none", "stripe")) + # 2022无图案,2023用条纹图案 labs(x="Genotype", y="Yield") + theme_classic(base_size=18, base_family="serif") + theme(legend.position="right", legend.title=element_blank(), legend.key=element_rect(color="white", fill="white"), legend.text=element_text(family="serif", face="plain", size=15, color="black"), legend.background= element_rect(fill="white"), axis.line = element_line(linewidth = 0.5, colour="black"))+ guides(fill="none") # 隐藏基因型填充图例
关键调整说明:
- 使用
geom_bar_pattern替代geom_bar,通过pattern=Season将季节映射为不同填充图案 - 用
scale_pattern_manual设置不同季节对应的图案(可选图案包括stripe、crosshatch、dot等) - 同样通过
guides(fill="none")隐藏基因型的填充图例
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

