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

geom_col绘制月降水量图时X轴刻度未对齐柱状图求助

解决geom_col柱状图与X轴刻度不对齐的问题

核心问题分析

你的X轴用的是连续型POSIXct时间变量,ggplot会自动生成常规时间刻度(比如每月1号),但你的柱状图是基于每个数据点的具体日期(比如3月14日、4月14日)绘制的,两者位置不匹配导致错位。如果近期ggplot包有自动更新,默认刻度生成逻辑的变化也可能是问题突然出现的原因。

两种可行解决方案

方案一:改用分类变量映射X轴(推荐)

既然是月度汇总数据,直接用数据中的Month列作为X轴,柱子和标签会完全对齐:

json %>% 
  filter(Station == "26_2_1_150_744") %>%
  filter(Date >= "2025-03-01 00:00:00" & Date <= "2025-06-15") %>%
  ggplot(aes(x = Month, y = measure)) + 
  geom_col(fill = "dodgerblue3") +
  ylim(0, 300) + 
  labs(x = "", y = "") + 
  # 注释的x坐标对应Month的位置(第4个为juin)
  annotate("text", x = 4, y = min_data + 15, label = "Ongoing", size = 9) + 
  annotate("text", x = Inf, y = Inf, label = "Station", vjust = 2, hjust = 1.08, size = 13) +
  theme_bw() + 
  theme(axis.text.x = element_text(size = 35), 
        axis.text.y = element_text(size = 35))

方案二:保留时间轴,手动指定刻度位置

如果需要保留时间轴的连续性,通过scale_x_datetime强制刻度对齐柱子的实际日期:

json %>% 
  filter(Station == "26_2_1_150_744") %>%
  filter(Date >= "2025-03-01 00:00:00" & Date <= "2025-06-15") %>%
  ggplot(aes(x = Date, y = measure)) + 
  geom_col(fill = "dodgerblue3") +
  scale_x_datetime(
    breaks = ~unique(.x), # 用数据中的Date作为刻度位置
    labels = ~format(.x, "%b") # 自定义标签为月份缩写,可按需修改
  ) +
  ylim(0, 300) + 
  labs(x = "", y = "") + 
  annotate("text", x = as.POSIXct("2025-06-05 12:00:00"), y = min_data + 15, label = "Ongoing", size = 9) + 
  annotate("text", x = as.POSIXct(Inf), y = Inf, label = "Station", vjust = 2, hjust = 1.08, size = 13) +
  theme_bw() + 
  theme(axis.text.x = element_text(size = 35), 
        axis.text.y = element_text(size = 35))

额外注意点

  • 代码中scale_colour_manual(name = "")属于冗余代码,没有在aes中映射颜色变量,可直接删除。
  • 确保min_data变量已正确定义,否则注释文本会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:24:53