如何使用geom_bar在x轴展示两个分类变量并添加区域分隔线
实现方案
你可以通过geom_vline()添加垂直分隔线,搭配annotate()添加分组标签即可实现需求,修改后的完整可运行代码如下:
library(dplyr) library(ggplot2) data <- tibble::tribble( ~code, ~term, ~estimate, ~std.error, ~statistic, ~p.value, ~region, "ANTA", "t_chla", 0.0577051712200805, 0.000720537559840254, 80.0862778518777, 1.51491004165028e-36, "Polar", "ARCH", "t_chla", 0.0528096415790542, 0.00237431411186973, 22.2420619559337, 9.38778083531695e-08, "Equatorial", "ARCT", "t_chla", 0.0381489725623347, 0.000549351930679462, 69.4435942277484, 7.1661522966813e-84, "Polar", "BPLR", "t_chla", 0.0334314725309052, 0.000908084662707285, 36.8153696498248, 6.728272457306e-26, "Polar", "EMED", "t_chla", 0.048713647973686, 0.00179735526256328, 27.1029601038437, 1.37127584382531e-20, "Temperate", "SANT", "t_chla", 0.0311278181792805, 0.000594175450783383, 52.3882602996143, 4.93281235468381e-67, "Polar", "SPSG", "t_chla", 0.0676467149977894, 0.00461643829029263, 14.653442923744, 1.64755108560374e-06, "Equatorial", "WMED", "t_chla", 0.0359293074812375, 0.000954627809780489, 37.6369796826883, 1.88418982949485e-42, "Temperate" ) data$code <- factor(data$code, levels = c("ANTA", "SANT", "ARCT", "BPLR", "EMED", "WMED", "SPSG", "ARCH")) # 计算标签y轴位置,避免遮挡柱子和误差线 label_y <- max(data$estimate + data$std.error) * 1.1 ggplot(data)+ geom_bar(aes(y = estimate, x = code, fill = code), stat = "identity")+ geom_errorbar(aes(ymin = estimate - std.error, ymax = estimate + std.error, x = code))+ # 添加垂直分隔线 geom_vline(xintercept = c(4.5, 6.5), linetype = "dashed", color = "gray60", linewidth = 0.8)+ # 添加分组标签 annotate("text", x = c(2.5, 5.5, 7.5), y = label_y, label = c("Polar", "Temperate", "Equatorial"), size = 4.5)+ scale_fill_brewer(palette = "Set1", guide = "none")+ theme_bw()+ ylab("Specific absorption")+ xlab("Oceanic province")+ ggtitle("Specific absorption")
逻辑说明
ggplot中离散的x轴因子会被自动映射为从1开始的整数位置,你设置的code顺序对应位置1~8:
- BPLR是第4个位置、EMED是第5个位置,分界点为4.5;WMED是第6个位置、SPSG是第7个位置,分界点为6.5,传入
geom_vline的xintercept参数即可添加分隔线 - 分组标签的x位置取对应分组的中点:Polar覆盖14,中点为2.5;Temperate覆盖56,中点为5.5;Equatorial覆盖7~8,中点为7.5,y值可以根据展示需求自行调整高度
- 你可以修改
linetype、color、size等参数自定义分隔线和标签的样式。
内容的提问来源于stack exchange,提问作者Flavien PETIT
相关产品推荐
相关产品推荐

