R语言ggplot双Y轴组合图中柱状图不显示的问题排查
解决ggplot双Y轴组合图中柱状图不显示的问题
问题背景
使用ggplot绘制包含柱状图与折线图的双Y轴组合图时,柱状图完全未显示。相关信息如下:
输入数据
reshaped_data <- structure(list( Year = c("2014", "2014", "2016", "2016", "2019", "2019", "2022", "2022"), Total_percentage = c(0.23, 0.23, 0.21, 0.21, 0.21, 0.21, 0.18, 0.18), Type = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), levels = c("Export", "Import"), class = "factor"), Value = c(1020494000, 1334758000, 1243093000, 1734937000, 1551107000, 2155641000, 2257669000, 2433288000)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))
原代码
ggplot(data = reshaped_data, aes(x = Year)) + geom_col(aes(y = Total_percentage, fill = "Total_percentage"), position = "dodge") + geom_line(aes(y = Value, color = Type, group = Type), size = 1) + geom_point(aes(y = Value, color = Type, group = Type), size = 3) + labs( title = "Total Percentage of Household Coffee Consumption against Coffee Trades in Malaysia From 2014 to 2022", x = "Year (2014-2022)", y = "Number of Trades (RM)" ) + coord_cartesian(ylim = c(0, 2500000000)) + scale_y_continuous( labels = scales::comma, breaks = seq(0, 2500000000, by = 500000000), sec.axis = sec_axis( trans = ~ (. / 1e9) * 10, # Convert to percentage name = "Total Percentage of Household Coffee Consumption", labels = scales::percent_format(scale = 0.01) ) ) + scale_fill_discrete(name = "Total Percentage of Household Coffee Consumption") + scale_color_manual( values = c("Import" = "#B2533E", "Export" = "#B5CB99"), name = "Type of Trades" )
效果对比
- 当前输出:仅显示折线图与散点,柱状图因数值过小完全不可见
- 预期输出:同时显示对应右侧百分比轴的柱状图,以及对应左侧贸易额轴的折线图
原因分析
- 数值范围差距过大:柱状图的
Total_percentage值在0.18-0.23之间,主Y轴范围却是0到25亿,数量级差达9个量级,导致柱状图被压缩成一条线。 - 双Y轴转换逻辑倒置:副轴是将主Y轴数值转成百分比,但柱状图直接用原始百分比值映射主Y轴,未做反向转换,数值不在主Y轴可视范围内。
修正后的代码
library(ggplot2) library(scales) # 对年份的百分比数据去重,避免重复绘制重叠柱子 unique_perc <- reshaped_data[!duplicated(reshaped_data$Year), c("Year", "Total_percentage")] ggplot() + # 柱状图:将百分比转换为主Y轴对应数值(副轴转换的逆运算) geom_col(data = unique_perc, aes(x = Year, y = Total_percentage * 1e9 / 10, fill = "Total_percentage"), width = 0.5) + # 折线图与散点图 geom_line(data = reshaped_data, aes(x = Year, y = Value, color = Type, group = Type), size = 1) + geom_point(data = reshaped_data, aes(x = Year, y = Value, color = Type, group = Type), size = 3) + labs( title = "马来西亚家庭咖啡消费占比与咖啡贸易额对比(2014-2022)", x = "年份(2014-2022)", y = "贸易额(马币)" ) + coord_cartesian(ylim = c(0, 2500000000)) + scale_y_continuous( labels = comma, breaks = seq(0, 2500000000, by = 500000000), sec.axis = sec_axis( trans = ~ (. / 1e9) * 10, name = "家庭咖啡消费占比", labels = percent_format(scale = 0.01) ) ) + scale_fill_manual(values = "#7F7F7F", name = "家庭咖啡消费占比") + scale_color_manual( values = c("Import" = "#B2533E", "Export" = "#B5CB99"), name = "贸易类型" ) + theme_minimal()
关键修正点
- 对百分比数据去重,每个年份仅保留一个值,避免重复绘制柱子导致重叠
- 将柱状图的
y值按Total_percentage * 1e9 / 10转换,让百分比数值匹配主Y轴范围 - 优化标题与标签为中文,提升可读性
- 为柱状图指定填充色,避免默认配色冲突
内容的提问来源于stack exchange,提问作者Nur Husnina
相关产品推荐
相关产品推荐

