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

如何在ggplot2的geom_line中使用平均值绘制柱状折线图?

在ggplot双轴图中为折线使用温度平均值的解决方案

问题背景

需要制作结合降水柱状图与温度平均值折线图的双轴图表,原代码未实现温度平均值的计算,且双轴转换采用硬编码方式不够灵活。

解决步骤

  1. 数据预处理:按日期分组,计算每日降水总量与温度平均值
    使用dplyr工具对原始数据进行聚合,确保每个日期对应唯一的降水总量和温度平均值:

    library(dplyr)
    library(ggplot2)
    
    # 处理数据,按日期聚合计算
    df_processed <- df %>%
      group_by(Date) %>%
      summarize(
        Total_Rain = sum(Rain, na.rm = TRUE),
        Avg_Temperature = mean(Temperature, na.rm = TRUE)
      )
    
  2. 计算双轴转换系数:
    为让温度折线适配左侧降水轴的范围,动态计算转换因子,替代硬编码:

    # 基于数据范围计算转换系数
    temp_range <- range(df_processed$Avg_Temperature, na.rm = TRUE)
    rain_range <- range(df_processed$Total_Rain, na.rm = TRUE)
    scale_factor <- (rain_range[2] - rain_range[1]) / (temp_range[2] - temp_range[1])
    intercept <- rain_range[1] - temp_range[1] * scale_factor
    
  3. 绘制双轴图表:
    使用处理后的数据,柱状图展示降水总量,折线图展示转换后的平均温度,同时配置双轴样式:

    ggplot(df_processed, aes(x = Date)) +
      # 降水柱状图
      geom_col(aes(y = Total_Rain), fill = "steelblue") +
      # 温度平均值折线图(转换到左侧轴)
      geom_line(aes(y = intercept + Avg_Temperature * scale_factor), 
                size = 1.5, color = "red") +
      # 双轴配置
      scale_y_continuous(
        name = "Precipitation",
        sec.axis = sec_axis(
          trans = ~(. - intercept)/scale_factor,
          name = "Average Temperature"
        )
      ) +
      # 轴样式调整
      scale_x_discrete(guide = guide_axis(angle = 90)) +
      theme(
        axis.line.y.right = element_line(color = "red"),
        axis.ticks.y.right = element_line(color = "red"),
        axis.text.y.right = element_text(color = "red"),
        axis.title.y.right = element_text(color = "red")
      ) +
      labs(title = "Daily Precipitation vs Average Temperature")
    

关键说明

  • 数据预处理确保折线图使用每日温度平均值,匹配需求;
  • 动态转换系数让双轴映射更贴合数据实际范围,比硬编码更可靠;
  • 右侧轴采用左侧转换的逆运算,保证温度数值展示准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:59:54