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

R ggplot2分组条形图:为每个柱子添加下方日期标签的问题

解决ggplot2分组条形图的日期标签与分组名称隐藏问题

需求说明

使用ggplot2绘制分组条形图,需满足:

  • 按dates分组,每组包含对应group(A-E)的柱子
  • 组内柱子颜色与group对应(硬性要求)
  • 横轴下方仅显示dates标签,隐藏group的分组名称

数据与现有代码

数据框:

df <- data.frame(
  dates = c('2022-01-01', '2022-01-01', '2022-01-01', '2022-01-01', '2022-01-01', 
            '2022-02-01', '2022-02-01', '2022-02-01', '2022-02-01', '2022-02-01', 
            '2022-03-01', '2022-03-01', '2022-03-01', '2022-03-01', '2022-03-01'),
  group = c('A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'),
  value = c(1.4, 0.2, 0.3, 0, -0.2, 1.4, 0.3, 0.2, 0.2, 0.5, 1, 0, 0, 0, 0.4)
)

现有绘图代码:

ggplot(df, aes(group=dates, y=value, x=group, fill=group)) +
    geom_bar(width = 0.8, position = position_dodge(width = 0.9), stat="identity", color="black") +
    scale_fill_manual(values=c("#E03225", "#EB6121", "#7F7F7F", "#F5F5F5", "#000000"), name = "") +
    scale_x_discrete(labels= c("", "", "", "", "")) + # 隐藏group标签
    xlab("") + 
    ylab("") + 
    theme_minimal() + 
    theme(legend.position="bottom", legend.direction = "horizontal")

解决方案

通过手动计算x轴位置,将日期标签放在每组柱子的中间位置,同时完全隐藏group相关的横轴标签:

library(ggplot2)

# 为每个日期分组设置中间基准位置
date_levels <- unique(df$dates)
df$date_center <- match(df$dates, date_levels) * 5 - 2  # 每组5个柱子,基准点取中间位置

# 为每个group分配偏移量,让柱子围绕日期基准点排列
group_offsets <- c(-2, -1, 0, 1, 2)  # A到E分别对应左到右的偏移
df$x_pos <- df$date_center + group_offsets[match(df$group, c('A','B','C','D','E'))]

ggplot(df, aes(x = x_pos, y = value, fill = group)) +
  geom_bar(width = 0.8, stat = "identity", color = "black") +
  # 保留原有的颜色配置
  scale_fill_manual(values = c("#E03225", "#EB6121", "#7F7F7F", "#F5F5F5", "#000000"), name = "") +
  # 设置x轴刻度为日期分组的中间位置,标签为日期
  scale_x_continuous(
    breaks = unique(df$date_center),
    labels = date_levels
  ) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.direction = "horizontal",
    # 隐藏x/y轴标题
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    # 隐藏x轴的小刻度线
    axis.ticks.x = element_blank()
  )

代码说明

  1. 计算x轴位置:通过date_center为每个日期分组设置中间基准点,再给每个group分配偏移量,让同一日期的5个柱子围绕基准点排列。
  2. 设置x轴刻度:仅在每组的中间位置显示日期标签,完全跳过group的相关标签。
  3. 主题调整:隐藏多余的轴标题和刻度线,保持图表简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:47:39