You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ggplot柱状图的Treatment标签从图例移至对应柱子下方?

将ggplot2柱状图的Treatment标签移至对应柱子的x轴下方

问题描述

现有一段生成玉米发芽率柱状图的ggplot2代码:

fillggp <- ggplot(corn_germ, aes(x=Day, y=PercentGermination, fill = Treatment)) + 
  geom_bar(stat= "identity",position = position_dodge(), colour= "black") + 
  theme_classic() + 
  theme(axis.title.x = element_text(color="black", size=12, margin = margin(t=10)),
        axis.title.y = element_text(color="black", size=12, margin = margin(r = 10)))

fillggp <- fillggp + scale_y_continuous(breaks= pretty_breaks(), limits=c(0, 1.2)) + 
  labs(x ="Day", y = "Percent Germination")
fillggp

当前图表的Treatment标签显示在图例中,希望将其移至每个对应柱子的x轴下方。尝试使用facet_grid方法时:

fillggp +
  facet_grid(~Treatment, switch = "x", scales = "free_x", space = "free_x") +
  theme(panel.spacing = unit(0, "lines"), 
        strip.background = element_blank(),
        strip.placement = "outside") 

结果是按Treatment分组Day,与需求相反。

解决方案

要实现按Day分组,每个Day下的柱子对应Treatment,且Treatment标签显示在柱子正下方,Day标签显示在分组上方,可以调整分面的分组变量和x轴映射:

ggplot(corn_germ, aes(x = Treatment, y = PercentGermination, fill = Treatment)) +
  geom_bar(stat = "identity", colour = "black") +
  # 按Day分面,将分面标签移至x轴上方作为分组标题
  facet_grid(~Day, switch = "x", scales = "free_x", space = "free_x") +
  scale_y_continuous(breaks = pretty_breaks(), limits = c(0, 1.2)) +
  labs(x = NULL, y = "Percent Germination") +
  theme_classic() +
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_text(color = "black", size = 12, margin = margin(r = 10)),
    # 移除分面背景,将Day标签置于x轴外侧
    strip.background = element_blank(),
    strip.placement = "outside",
    strip.text.x = element_text(color = "black", size = 12, margin = margin(t = 5)),
    # 取消分面之间的间距
    panel.spacing = unit(0, "lines"),
    # 隐藏图例(Treatment标签已在x轴显示)
    legend.position = "none"
  )

关键调整说明

  • 把x轴映射从Day改为Treatment,让每个分面(对应单个Day)内的柱子直接对应不同的Treatment类型。
  • 用facet_grid(~Day, switch = "x")将Day的标签移至x轴上方,作为分组标题,替代原x轴的Day标签。
  • 启用scales = "free_x"和space = "free_x"保证每个分面的宽度适配内容。
  • 隐藏图例,因为Treatment的分类标签已经直接显示在对应柱子的下方,无需重复展示。

内容的提问来源于stack exchange,提问作者Rylee Swiderek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:10:06