如何用ggplot绘制单组宽柱前置三组窄柱的分组柱状图?
实现单组宽柱+三组窄柱前置的分组柱状图
要实现你要的效果,核心思路是拆分数据分两次绘制柱状图,分别设置不同的柱子宽度和位置,具体代码如下(假设你要把cohort中第一个类别设为宽柱,其余三组为窄柱,可根据实际情况替换筛选条件):
cols4 <- c("#565656", "#0065c4", "#f03b20", "#73c400") # 拆分数据:窄柱组(除目标宽柱外的三组)、宽柱组(目标组) narrow_data <- subset(Table_for_Plot, cohort != names(cols4)[1]) wide_data <- subset(Table_for_Plot, cohort == names(cols4)[1]) rhoc_plot <- ggplot() + # 先画窄柱组:宽度设小,position_dodge匹配宽度,x轴向左偏移让柱子前置 geom_bar(data = narrow_data, aes(x = as.numeric(marker) - 0.2, y = rho_c, fill = cohort), stat = "identity", width = 0.2, position = position_dodge(width = 0.2)) + # 再画宽柱组:宽度设大,用原始x位置 geom_bar(data = wide_data, aes(x = as.numeric(marker), y = rho_c, fill = cohort), stat = "identity", width = 0.4) + theme_classic() + theme(axis.text.x = element_text(angle = 45, hjust = 1), axis.title.x = element_blank(), axis.ticks.x = element_blank()) + scale_y_continuous(expand = c(0, 0.0001)) + ylab("rho c") + scale_fill_manual(values = cols4) + # 调整x轴刻度,对应原始marker的标签和位置 scale_x_continuous(breaks = seq_along(unique(Table_for_Plot$marker)), labels = unique(Table_for_Plot$marker))
关键细节说明:
- 数据拆分:把需要不同宽度的柱子分开处理,避免统一的
position_dodge限制 - 位置偏移:通过
as.numeric(marker) - 0.2把窄柱组整体左移,确保它们在宽柱前方 - 宽度匹配:窄柱的
width和position_dodge(width)保持一致,保证三组窄柱正常并列 - x轴调整:用
scale_x_continuous把数值化的x轴映射回原始的marker标签,避免坐标轴混乱
你可以根据实际需求调整偏移量(0.2)、窄柱宽度(0.2)和宽柱宽度(0.4),直到达到理想的视觉效果。
内容的提问来源于stack exchange,提问作者user18632888
相关产品推荐
相关产品推荐

