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

在R中绘制多轴分面列图:复刻十年月度海平面统计图

按十年分组绘制月度海平面统计柱形图的解决方案

你需要复刻指定样式的统计图,目前已基于ggplot2的geom_col()写出初始代码,但不知道如何按十年分组拆分数据、按月份绘制并排列成目标布局。以下是完整实现步骤和代码:

核心思路

  • 确保数据包含decade(十年分组)字段,用于分面排版
  • 将mediansealevelmonth和minsealevelmonth转为长格式数据,统一映射可视化属性
  • 用分面函数按十年拆分子图,调整柱形样式区分中位数与最小值

完整代码

# 加载依赖包
library(ggplot2)
library(tidyr)

# 转换数据为长格式(假设数据框sealeveldecade包含decade、month、mediansealevelmonth、minsealevelmonth字段)
sealevel_long <- sealeveldecade %>%
  pivot_longer(
    cols = c(mediansealevelmonth, minsealevelmonth),
    names_to = "stat_type",
    values_to = "sea_level"
  )

# 绘制目标样式图表
ggplot(sealevel_long, aes(x = month, y = sea_level, fill = stat_type)) +
  # 设置柱形并排显示,避免重叠
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # 按十年分面,控制子图排列行数
  facet_wrap(~decade, nrow = 2) +
  # 自定义颜色与图例标签
  scale_fill_manual(
    values = c("mediansealevelmonth" = "#2c3e50", "minsealevelmonth" = "#3498db"),
    labels = c("月度中位数海平面", "月度最低海平面")
  ) +
  # 设置图表标签
  labs(
    x = "月份",
    y = "海平面高度(cm,基于RH2000)",
    title = "1960-2009年各月份海平面中位数与最小值统计",
    subtitle = "基于每日24小时测量数据",
    fill = "统计类型"
  ) +
  # 优化主题样式
  theme_minimal() +
  theme(
    strip.text = element_text(face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

关键细节说明

  • pivot_longer():将宽格式数据转为长格式,让中位数和最小值共享坐标轴映射,便于用颜色区分类别
  • position_dodge():让同一月份的两个柱形并排展示,解决重叠问题
  • facet_wrap():按十年分组生成独立子图,nrow参数可根据目标布局调整行数;若需按行列严格排列,可改用facet_grid(rows = ~decade)或facet_grid(cols = ~decade)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:30:05