ggplot2绘制柱状图时geom_text报错:缺失x、y美学映射的技术问询
解决geom_text缺失x、y美学的错误
错误原因
你的代码里geom_col仅在自身图层内定义了x和y的美学映射,没有将其设置为全局映射,导致后续的geom_text无法读取这两个必要参数,因此抛出缺失美学的错误。
两种修正方案
方案1:使用全局美学映射(推荐)
把x和y的映射放到ggplot()函数中,让所有图层共享这些参数,避免重复代码:
ggplot(average_sleep_per_day, aes(x = reorder(day, average_sleep), y = average_sleep)) + geom_col(aes(fill = average_sleep)) + labs(title = "average_sleep_per_day") + theme_classic() + theme(panel.background = element_blank(), plot.title = element_text(hjust = 0.5, size=10, face = "bold")) + geom_text(aes(label = round(average_sleep, 1)), position = position_stack(vjust = 1.02))
方案2:在geom_text中显式指定x、y
如果不想用全局映射,就在geom_text的aes里明确补充x和y的定义:
ggplot(average_sleep_per_day) + geom_col(aes(x = reorder(day, average_sleep), y = average_sleep, fill = average_sleep)) + labs(title = "average_sleep_per_day") + theme_classic() + theme(panel.background = element_blank(), plot.title = element_text(hjust = 0.5, size=10, face = "bold")) + geom_text(aes(x = reorder(day, average_sleep), y = average_sleep, label = round(average_sleep, 1)), position = position_stack(vjust = 1.02))
验证效果
用你提供的average_sleep_per_day数据运行修正后的代码,就能生成带有日均睡眠时间标签的柱状图,标签会准确显示在对应柱子的上方。
内容的提问来源于stack exchange,提问作者Fokou Serges
相关产品推荐
相关产品推荐

