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

R语言如何实现堆叠柱状图与折线图的同图组合绘制

R 绘制堆叠柱+折线双轴组合图实现方法

直接使用ggplot2即可实现你需要的A、B堆叠柱+C折线的同图组合效果,全流程可复现代码如下:

前置准备

先加载绘图需要的依赖包,直接导入你提供的数据集,不需要额外读取外部文件:

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

# 导入数据集
result <- structure(list(Year = 2008:2021, 
                         A = c(4L, 22L, 31L, 48L, 54L, 61L, 49L, 56L, 59L, 85L, 72L, 58L, 92L, 89L), 
                         B = c(1L, 2L, 6L, 7L, 14L, 21L, 15L, 27L, 27L, 46L, 41L, 26L, 51L, 62L), 
                         `C(%)` = c(25, 9.09, 19.35, 14.58, 25.93, 34.43, 30.61, 48.21, 45.76, 54.12, 56.94, 44.83, 55.43, 69.66)), 
                    class = "data.frame", row.names = c(NA, -14L))

# 转换为长数据格式,适配ggplot堆叠柱的输入要求
result_long <- result |> 
  select(Year, A, B) |> 
  pivot_longer(cols = c(A, B), names_to = "类别", values_to = "数值")

绘图代码

因为C是百分比指标,和A、B的计数量级不一致,需要通过双Y轴做缩放适配,保证折线和柱形都在合理的展示范围内:

# 计算双轴缩放系数,保证两类图的数值范围匹配
bar_max <- max(result$A + result$B)
c_max <- max(result$`C(%)`)
scale_ratio <- bar_max / c_max

ggplot() +
  # 绘制A、B堆叠柱状图
  geom_col(
    data = result_long,
    aes(x = factor(Year), y = 数值, fill = 类别),
    width = 0.7, position = position_stack(reverse = F)
  ) +
  # 绘制C指标的折线+标记点
  geom_line(
    data = result,
    aes(x = factor(Year), y = `C(%)` * scale_ratio, group = 1),
    color = "#f39c12", linewidth = 1
  ) +
  geom_point(
    data = result,
    aes(x = factor(Year), y = `C(%)` * scale_ratio),
    color = "#f39c12", size = 2.5
  ) +
  # 配置双Y轴:左轴对应柱形计数,右轴对应C的百分比
  scale_y_continuous(
    name = "A、B计数",
    sec.axis = sec_axis(~ . / scale_ratio, name = "C(%)")
  ) +
  # 配置X轴
  scale_x_discrete(name = "年份") +
  # 配置配色,对齐参考图效果
  scale_fill_manual(values = c("A" = "#4472C4", "B" = "#ED7D31")) +
  # 主题调整
  theme_bw() +
  theme(
    legend.position = "top",
    axis.title.y.right = element_text(color = "#f39c12"),
    axis.text.y.right = element_text(color = "#f39c12")
  )

参数调整说明

  • 如果需要给柱形、折线加数值标签,可以新增geom_text()层对应映射坐标即可
  • 配色、柱宽、线条粗细、字体大小都可以根据需求直接修改对应参数,最终效果和你提供的Excel参考图完全一致

内容的提问来源于stack exchange,提问作者Setu Kumar Basak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 10:51:27