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

如何在ggplot中实现分组柱状图+折线图?请求代码修正

问题分析与解决方案

原代码的折线图无法显示,核心原因是百分比数值(0.9左右)与柱状图的数值(1000+)量级差距过大,导致折线被压缩在图表底部,同时没有配置次坐标轴来适配百分比的刻度范围。以下是修正后的完整代码及说明:

修正后的代码

library(tidyverse)

dat = data.frame(
  stringsAsFactors = FALSE,
  Monthly = c("22-Mar","22-Apr","22-May",
              "22-Jun","22-Jul","22-Aug","22-Sep","22-Oct","22-Nov",
              "22-Dec","23-Jan","23-Feb","23-Mar","23-Apr"),
  Eligible = c(1374L,1336L,1410L,1419L,
               1418L,1420L,1137L,1358L,1358L,1409L,1419L,1409L,
               1358L,1415L),
  Documented = c(1260L,1299L,1370L,1375L,
                 1376L,1380L,1116L,1332L,1332L,1386L,1401L,1381L,
                 1339L,1398L)
)

# 计算百分比,仅将Eligible和Documented转为长格式,单独保留百分比数据
dat_long = dat %>% 
  mutate(Percentage = round(Documented/Eligible, 2)) %>% 
  pivot_longer(cols = c(Eligible, Documented), names_to = "Category", values_to = "Count")

# 转换月份为因子,保证时间顺序正确
dat_long$Monthly = factor(dat_long$Monthly,
                          levels = c("22-Mar","22-Apr","22-May","22-Jun","22-Jul",
                                     "22-Aug","22-Sep","22-Oct","22-Nov","22-Dec",
                                     "23-Jan","23-Feb","23-Mar","23-Apr"))

# 获取柱状图的最大值,用于百分比数值的量级转换
max_count = max(dat_long$Count)

# 绘制组合图表
ggplot() +
  # 绘制分组柱状图:展示Eligible和Documented的人数
  geom_col(data = dat_long, 
           aes(x = Monthly, y = Count, fill = Category), 
           position = "dodge", width = 0.7) +
  # 绘制折线图:展示覆盖率百分比,先将数值转换为与柱状图同量级范围
  geom_line(data = distinct(dat_long, Monthly, Percentage), 
            aes(x = Monthly, y = Percentage * max_count, group = 1), 
            color = "red", size = 1.2) +
  # 添加折线数据点,增强可读性
  geom_point(data = distinct(dat_long, Monthly, Percentage), 
             aes(x = Monthly, y = Percentage * max_count), 
             color = "red", size = 2) +
  # 设置主坐标轴(人数)和次坐标轴(覆盖率百分比)
  scale_y_continuous(
    name = "人数",
    sec.axis = sec_axis(~ . / max_count, name = "覆盖率(%)", labels = function(x) paste0(x*100, "%"))
  ) +
  # 设置柱状图的灰度配色
  scale_fill_grey(start = 0.3, end = 0.8) +
  # 主题调整,优化视觉效果
  theme_bw() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position = "top"
  )

关键修正点说明

  • 数据处理优化:不再将百分比与计数变量放在同一长格式列中,避免数值量级冲突,单独提取百分比数据进行处理。
  • 次坐标轴配置:通过sec_axis()创建次坐标轴,先将百分比数值乘以计数的最大值转换为同量级范围,再通过反转转换将刻度标签显示为百分比格式。
  • 折线图映射:使用group=1确保折线可以正确连接所有月份的点,避免因分组问题导致折线断裂。
  • 视觉优化:调整柱状图宽度、折线颜色和大小,旋转x轴标签避免重叠,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:52:10