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

如何在R中绘制按月分组的月均河流流量柱状图?

按月分组绘制月均河流流量柱状图(R实现)

步骤1:加载所需工具包

首先加载数据处理和绘图的核心包:

library(dplyr)
library(ggplot2)
library(lubridate) # 用于日期处理,也可以用stringr替代

步骤2:数据预处理

将原始的month字符列转换为日期格式,提取月份信息(名称或数字),方便后续分组:

# 假设你的数据框名为df
df <- df %>%
  mutate(
    # 将month列转为日期格式
    date = ymd(paste0(month, "-01")),
    # 提取中文月份名称
    month_name = month(date, label = TRUE, abbr = FALSE, locale = "zh_CN.UTF-8")
  )

如果不想用lubridate,也可以用stringr直接提取月份并转换为标签:

library(stringr)
df <- df %>%
  mutate(
    month_num = str_sub(month, 6, 7),
    month_name = factor(month_num, 
                       levels = sprintf("%02d", 1:12),
                       labels = c("一月", "二月", "三月", "四月", "五月", "六月",
                                  "七月", "八月", "九月", "十月", "十一月", "十二月"))
  )

步骤3:按月分组并绘图

根据需求选择合适的柱状图类型:

类型1:各月平均流量柱状图(最常用)

将所有年份的同一月份数据聚合为平均值,绘制每个月份的平均流量:

# 按月分组计算平均流量
monthly_summary <- df %>%
  group_by(month_name) %>%
  summarise(avg_discharge = mean(average_discharge, na.rm = TRUE))

# 绘制柱状图
ggplot(monthly_summary, aes(x = month_name, y = avg_discharge)) +
  geom_col(fill = "#3498db", alpha = 0.8) +
  labs(
    title = "1936-2022年各月平均河流流量",
    x = "月份",
    y = "平均流量"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

类型2:各年份同月份流量对比柱状图

如果需要展示每个年份同一月份的流量差异,可以用分面方式(年份较多时分面更清晰):

# 提取年份
df <- df %>% mutate(year = year(date))

# 分面绘制各月份的年度流量柱状图
ggplot(df, aes(x = factor(year), y = average_discharge)) +
  geom_col(fill = "#e74c3c", alpha = 0.7) +
  facet_wrap(~month_name, scales = "free_y") +
  labs(
    title = "1936-2022年各月份河流流量年度对比",
    x = "年份",
    y = "月均流量"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.text.x = element_text(angle = 90, size = 8)
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:33:15