如何修改ggplot分组百分比柱状图的顶部文本标签样式?
修正后完整可运行代码
library(ggplot2) # 示例数据集 df <- structure(list(year = c("2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018"), hours.48 = c("Yes", "No", "No", "No", "Yes", "No", "No", "No", "No", "No", "No", "No", "No", "No", "Yes", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No")), row.names = c(NA, 30L), class = "data.frame") ggplot(df, aes(x = hours.48, fill = hours.48)) + geom_bar(aes(y = (..count..)/sum(..count..) * 100), width = 0.7) + labs(x = "工作时长≥48小时", y = "员工占比%", fill = "工作时长≥48小时", title = "法规生效后") + theme_minimal() + scale_fill_manual(values = c("orange", "blue")) + geom_text(aes(label = paste0(round((..count..)/sum(..count..) * 100, 1), "%"), y = (..count..)/sum(..count..) * 100), stat= "count", vjust = -0.2, color = "white", size = 3.5) + theme(legend.position = "top")
修改说明
- 文本白色:在
geom_text参数中添加color = "white"直接设定文本颜色 - 保留1位小数:用
round()函数对计算得到的百分比值保留1位小数,拼接%符号符合百分比展示逻辑 - 位置对齐:将
geom_text的y坐标和geom_bar的y坐标统一为相同的百分比计算逻辑,替换原有错误的..prop..参数,配合vjust = -0.2微调文本与柱子顶部的间距
内容的提问来源于stack exchange,提问作者user3571389
相关产品推荐
相关产品推荐

