使用ggplot绘制多列数据的组合柱状图与折线图
用ggplot绘制多列组合柱状图+折线图的解决方案
1. 修正数据结构
原始数据框未包含Year列,首先需要将年份变量加入数据框,确保后续绘图时x轴能正确对应年份:
Year <- c(2014, 2015, 2016) one <- c(1000, 1100, 1200) two <- c(800, 900, 1100) three <- c(200,200,100) # 包含Year列的完整数据框 df <- data.frame(Year, one, two, three)
2. 转换数据格式(宽→长)
要绘制多列分组柱状图,需将宽格式数据转换为长格式,方便ggplot识别不同的柱子系列:
library(tidyr) library(ggplot2) # 提取要做柱状图的列(one和three),转换为长格式 df_long <- df %>% pivot_longer(cols = c(one, three), names_to = "Category", values_to = "Value")
3. 绘制基础组合图(单Y轴)
将分组柱状图和折线图组合,其中one和three作为柱状图系列,two作为折线图系列:
ggplot() + # 分组柱状图:按年份分组,不同类别填充不同颜色 geom_bar(data = df_long, aes(x = Year, y = Value, fill = Category), stat = "identity", position = position_dodge(width = 0.8)) + # 折线图:使用原数据的two列,group=1确保折线连接所有年份 geom_line(data = df, aes(x = Year, y = two, color = "two"), stat = "identity", linewidth = 1, group = 1) + # 添加折线标记点,提升可读性 geom_point(data = df, aes(x = Year, y = two, color = "two"), size = 3) + # 自定义图例名称 scale_fill_discrete(name = "柱状图系列") + scale_color_manual(name = "折线图系列", values = "#ff4500") + # 坐标轴与标题设置 labs(x = "年份", y = "数值", title = "组合柱状图与折线图") + # 简洁主题 theme_minimal()
4. 双Y轴组合图(处理数值范围差异)
如果two的数值范围和one/three差异较大,可添加双Y轴优化显示效果:
ggplot() + geom_bar(data = df_long, aes(x = Year, y = Value, fill = Category), stat = "identity", position = position_dodge(width = 0.8)) + # 缩放折线数值,使其适配左轴范围(系数需根据实际数据调整) geom_line(data = df, aes(x = Year, y = two * 1.2, color = "two"), stat = "identity", linewidth = 1, group = 1) + geom_point(data = df, aes(x = Year, y = two * 1.2, color = "two"), size = 3) + # 设置双Y轴:左轴对应柱状图,右轴反向缩放对应折线图 scale_y_continuous( name = "柱状图数值", sec.axis = sec_axis(~ . / 1.2, name = "折线图数值") ) + scale_fill_discrete(name = "柱状图系列") + scale_color_manual(name = "折线图系列", values = "#ff4500") + labs(x = "年份", title = "双Y轴组合图表") + theme_minimal()
关键说明
position_dodge()用于设置分组柱子的间距,避免重叠- 折线图必须指定
group=1,否则ggplot会将每个年份视为单独分组,无法连成折线 - 双Y轴的缩放系数需根据实际数据调整,确保折线和柱子的显示位置合理
内容的提问来源于stack exchange,提问作者Jan Jankowski Janek
相关产品推荐
相关产品推荐

