如何为双Y轴堆叠条形图的均价点添加独立图例?
解决ggplot2双Y轴图表独立图例问题
要实现堆叠条形图展示数量,同时添加带独立图例的均价黑点,核心是给均价点单独设置映射变量,避免和条形图的fill图例混淆,同时修正双Y轴的刻度对齐问题。
完整代码实现
library(dplyr) library(ggplot2) # 生成均价数据集,添加.groups参数消除分组警告 price.avg <- diamonds %>% group_by(cut, color) %>% summarise(price = mean(price), .groups = "drop") # 计算数量与价格的比例,用于双Y轴刻度适配 count_max <- diamonds %>% count(cut, color) %>% pull(n) %>% max() price_max <- price.avg %>% pull(price) %>% max() scale_factor <- count_max / price_max # 绘制图表 diamonds %>% ggplot() + # 堆叠条形图:按cut分组,clarity区分填充色 geom_bar(aes(x = cut, fill = clarity)) + facet_wrap(~ color, scale = "free_y") + # 均价点:添加color映射生成独立图例,用scale_factor转换价格适配数量轴范围 geom_point(data = price.avg, aes(x = cut, y = price * scale_factor, color = "average price"), shape = 16, size = 3) + # 配置双Y轴:左侧为数量,右侧还原为原始价格 scale_y_continuous( name = "Count", sec.axis = sec_axis(~ . / scale_factor, name = "Average Price") ) + # 设置均价点的颜色为黑色,图例名称自定义 scale_color_manual(values = "black", name = "") + # 调整图例样式:给均价点图例设置白色背景,区分clarity图例 guides( fill = guide_legend(title = "Clarity"), color = guide_legend( title = "average price", override.aes = list(fill = "white") ) ) + labs(x = "Cut") + theme_minimal()
关键调整说明
- 独立图例实现:在
geom_point的aes中加入color = "average price",创建独立的图例分组,避免和条形图的fill=clarity图例混合。配合scale_color_manual指定黑点颜色,再通过guides设置图例的白色背景。 - 双Y轴刻度对齐:由于数量和价格的数值范围差异极大,直接用原始价格会导致点超出图表范围。通过计算
scale_factor将价格转换为适配数量轴的范围,右侧Y轴再通过反向转换还原真实价格。 - 消除冗余警告:在
summarise后添加.groups = "drop",清理分组状态,消除dplyr的分组警告。
内容的提问来源于stack exchange,提问作者hnguyen
相关产品推荐
相关产品推荐

