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

R语言折线图x轴日期按3个月分组及双Y轴设置问题

R 绘制多系列折线图问题解决方案

1. 解决按3个月累计统计、图表拥挤问题

你之前的代码直接使用每日数据绘图,没有提前按3个月维度聚合统计,是造成图表拥挤的核心原因。你可以先使用dplyr+lubridate做数据预处理,按3个月粒度汇总每个受伤原因的总案例数:

# 加载依赖包
library(tidyverse)
library(lubridate)

# 按3个月维度聚合数据
df_agg <- df %>%
  # 将所有日期归到所属3个月区间的起始日期
  mutate(quarter_date = floor_date(Date, unit = "3 months")) %>%
  # 按区间+受伤原因分组求和
  group_by(quarter_date, Injury.Cause) %>%
  summarise(cum_n = sum(n, na.rm = TRUE), .groups = "drop")

# 可选:补齐缺失区间的0值,避免折线中断
df_agg <- df_agg %>%
  complete(quarter_date, Injury.Cause, fill = list(cum_n = 0))

2. 实现双Y轴刻度设置

ggplot2的次Y轴本质是主Y轴的线性映射,你需要先根据两个轴的最大值计算转换系数,再分别映射两类数据:

# 计算轴转换系数:右轴最大值/左轴最大值
y_trans_coef <- 150 / 80

ggplot() +
  # 绘制非道路交通事故的折线,对应左轴,用原始数值
  geom_line(
    data = df_agg %>% filter(Injury.Cause != "Road traffic accidents"),
    aes(x = quarter_date, y = cum_n, color = Injury.Cause)
  ) +
  # 绘制道路交通事故的折线,数值除以转换系数匹配左轴刻度
  geom_line(
    data = df_agg %>% filter(Injury.Cause == "Road traffic accidents"),
    aes(x = quarter_date, y = cum_n / y_trans_coef, color = Injury.Cause)
  ) +
  # X轴按要求设置3个月间隔、标签格式
  scale_x_date(
    date_breaks = "3 months",
    date_labels = "%Y %b",
    limits = c(min(df_agg$quarter_date), max(df_agg$quarter_date))
  ) +
  # Y轴设置:左轴对应其他受伤原因,右轴对应道路交通事故
  scale_y_continuous(
    name = "其他受伤原因案例数",
    limits = c(1, 80),
    breaks = seq(1, 80, 10),
    sec.axis = sec_axis(
      ~ . * y_trans_coef,
      name = "道路交通事故案例数",
      breaks = seq(1, 150, 10)
    )
  ) +
  labs(color = "受伤原因") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:06:05