如何用ggplot绘制右侧分组加宽的组合箱线图?
解决方法:调整不同区域箱线图宽度
要实现右侧(Photochemistry)箱线图比左侧(Gas exchange)更宽的效果,核心是给两个区域的箱线图绑定不同宽度参数,具体步骤如下:
1. 给数据添加区域标识列
先区分左右区域的x轴变量,给dff和df1添加区域标记列(假设前7个x变量属于Gas exchange区域,可根据实际变量位置调整判断条件):
# 给主数据框和文本数据框添加区域标识 dff$region <- ifelse(as.integer(dff$variable) <= 7, "gas", "photo") df1$region <- ifelse(as.integer(df1$variable) <= 7, "gas", "photo")
2. 修改ggplot代码,绑定宽度到区域
调整原代码中箱线图和误差线的宽度映射,同时修正文本的偏移对齐:
ggplot(dff, aes(x=variable, y=value, fill=Specie, width=region)) + stat_boxplot(geom = "errorbar", col="red")+ scale_fill_manual(values=c('#FFC7CE','#FFEB9C','#C6EFCF'))+ # 自定义左右区域箱线图宽度:左侧窄,右侧宽 scale_width_manual(values = c(gas = 0.6, photo = 0.8))+ geom_boxplot(outlier.shape = NA,linetype = 1)+ theme_bw()+ geom_text(data = df1, aes(y = up+0.02, label = label), fontface="italic", size=2.5, position = position_dodge(width = aes(width=region)), hjust=0.4, col="blue")+ theme(axis.text.x = element_text(size = 10, colour = "black", family = "serif"), axis.text.y = element_text(size = 10, colour = "black"), panel.grid.minor = element_blank(), legend.position = c(0.5, 1.05), legend.background = element_blank(), legend.direction = "horizontal", legend.title = element_blank(), legend.text = element_text(size = 9, face="italic", colour = "black")) + scale_x_discrete(labels=c(l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12)) + scale_y_continuous(breaks = seq(0, 1, 0.1),sec.axis = sec_axis(~.*1, breaks = seq(0, 1, 0.1))) + labs(title = "",subtitle = "",y = y, x = "")+ geom_vline(xintercept= 7.5, colour="black",linetype="dashed")+ geom_vline(xintercept= 12.5, colour="black",linetype="solid")+ annotate(geom="text", x=1.1, y=1.02, label="Gas exchange",family="serif", fontface="bold",size=3.5)+ annotate(geom="text", x=8.2, y=1.02, label="Photochemistry",family="serif", fontface="bold",size=3.5)
关键修改说明
- 在全局
aes中加入width=region,让箱线图宽度与区域绑定; - 用
scale_width_manual自定义宽度数值,gas对应左侧区域,photo对应右侧区域,数值越大箱线图越宽(可根据需求调整0.6/0.8这类数值); - 调整
geom_text的position_dodge参数为aes(width=region),确保标注文本与对应区域的箱线图对齐。
内容的提问来源于stack exchange,提问作者Ikram Bashir
相关产品推荐
相关产品推荐

