ggplot中使用percent(accuracy=3L)时百分比无法正确进位问题排查
解决ggplot百分比标签保留一位小数无效的问题
我来帮你排查问题!你遇到的情况是因为对scales::percent()里的accuracy参数理解有误——这个参数不是用来指定小数位数,而是控制数值舍入的精度步长。
问题根源
你写的accuracy = 3L会让百分比被舍入到最接近的3的倍数(比如56%会变成57%,22%变成21%),自然就显示成整数了,完全达不到保留一位小数的效果。
正确的参数设置
如果想让百分比标签保留一位小数,需要把accuracy设为0.1,这样数值会被舍入到小数点后一位:
geom_text(aes(label = scales::percent(prop, suffix = "", accuracy = 0.1)), position=position_dodge(width = 0.9), vjust = 0.4, hjust = -0.1, size = 5)
完整修改后的代码
把你的代码替换成下面这样,就能看到带一位小数的百分比标签了:
lebanon %>% filter(!is.na(challenge)) %>% count(challenge) %>% mutate(prop = n / sum(n)) %>% ggplot(aes(fct_reorder(challenge, prop), y = prop, fill = prop)) + geom_bar(stat = "identity", show.legend = FALSE) + scale_y_continuous(labels = scales::percent) + geom_text(aes(label = scales::percent(prop, suffix = "", accuracy = 0.1)), position=position_dodge(width = 0.9), vjust = 0.4, hjust = -0.1, size = 5) + labs(title = "What is the most important challenge facing Lebanon today?", x = "", y = "", fill = "") + theme_minimal() + theme(axis.text.x = element_text(size = 15), axis.text.y = element_text(size = 15), legend.text = element_text(size = 15), plot.title = element_text(size = 25), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank()) + coord_flip()
额外小技巧
如果你想强制显示固定小数位数(比如不管数值是什么都显示一位小数,比如56%显示成56.0%),也可以用scales::number_format()来实现,效果是一样的:
geom_text(aes(label = scales::number_format(accuracy = 0.1, suffix = "%")(prop)), # 其他参数不变 )
内容的提问来源于stack exchange,提问作者Nicosc
相关产品推荐
相关产品推荐

