如何在ggplot横向100%堆叠条形图旁添加均值文本?
解决ggplot堆叠条形图添加均值文本的报错问题
错误原因
你遇到的"Aesthetics must be either length 1 or the same as the data (32)"报错,是因为主绘图数据graph_data按manufacturer和class双重分组(共32行),而hwy_mean仅按manufacturer分组(共15行),两者行数不匹配,直接共用美学映射时就会出现长度不一致的问题。
修正步骤及完整代码
- 先修正原代码笔误:
left_join里的data应为mpg(原代码未定义data对象)。 - 给
geom_text单独指定hwy_mean数据集,同时因coord_flip()反转了坐标轴,需调整x/y的对应映射。
完整代码如下:
library(tidyverse) # 处理主绘图数据 graph_data = mpg %>% group_by(manufacturer, class) %>% summarise(count = n()) %>% left_join( mpg %>% group_by(manufacturer) %>% summarise(manufacturer_total = n()) ) # 计算hwy均值 hwy_mean = mpg %>% group_by(manufacturer) %>% summarise(mean_hwy = round(mean(hwy), digits = 2)) # 绘图并添加均值文本 graph_data %>% ggplot(aes(x = manufacturer, y = count/manufacturer_total, fill = class)) + geom_bar(position = 'stack', stat = 'identity') + # 添加均值文本,指定单独数据集,设置位置在条形右侧 geom_text(data = hwy_mean, aes(x = manufacturer, y = 1.02, label = mean_hwy), inherit.aes = FALSE) + # 关闭继承主图不匹配的美学映射 coord_flip() + scale_y_continuous(labels = scales::percent) # 可选:将y轴转为百分比格式
关键说明
inherit.aes = FALSE:必须设置该参数,避免继承主图中fill = class等不匹配的美学映射。y = 1.02:100%堆叠条形图的y轴最大值为1,设置y=1.02可把文本放在条形右侧外部,避免重叠。- 若想将文本放在条形内部右侧,可把
y值设为1,再搭配hjust = 1.1调整位置。
内容的提问来源于stack exchange,提问作者Sparkringo
相关产品推荐
相关产品推荐

