如何在ggplot2中将百分比四舍五入到小数点后两位 [英] How to round percentage to 2 decimal places in ggplot2
问题描述
我的代码生成此图:
代码:
ggplot(areas, aes(x = RETAILER, y = Difference), label=sprintf("%0.2f", round(areas$Difference, digits = 2))) +
geom_bar(stat = "identity", aes(fill = RETAILER), colour = "black") +
scale_y_continuous("Percentage", labels = percent_format()) +
geom_text(aes(label = paste(Difference * 100, "%"),
vjust = ifelse(Difference >= 0, -1.5, 1.5))) +
theme_classic()
我找到了使数据标签正确放置在每个小节上方或下方的代码,但是我似乎无法将值四舍五入到小数点后两位.
I have found code to allow the data labels to be positioned correctly above or below each bar, but I cannot seem to get the values to round to 2 decimal places.
我尝试了round(areas, 2)
和sprintf("%0.2f")
等其他方法,但是我尝试的任何方法似乎都无效,并且我确定我缺少一些简单的方法.
I have tried round(areas, 2)
and sprintf("%0.2f")
among other things, but nothing I try seems to work and I'm sure that I'm missing something simple.
我要去哪里错了?
更新:
有了罗兰的鼓励",我现在设法几乎解决了这个问题;现在的问题是我现在丢失了百分号:
With Roland's "encouragement", I have now managed to almost resolve this; the problem now is that I have now lost the percentage signs:
我如何找回他们?
更新的代码:
ggplot(areas, aes(x = RETAILER, y = Difference)) +
geom_bar(stat = "identity", aes(fill = RETAILER), colour = "black") +
scale_y_continuous("Percentage", labels = percent_format()) +
geom_text(aes(label = sprintf("%0.2f", areas$Difference * 100, "%"),
vjust = ifelse(Difference >= 0, -1.5, 1.5))) +
theme_classic()
推荐答案
ggplot2/scales
软件包的最新版本为scales::percent
函数提供了参数,例如将百分比四舍五入为整数:
Recent versions of ggplot2/scales
packages offer arguments to the scales::percent
function, for instance to round percentages to integers:
scale_y_continuous(labels = scales::percent_format(accuracy = 1L))
这大致等同于round(x, 0L)
:请注意1
而不是0
.
This is roughly equivalent to round(x, 0L)
: Note the 1
instead of 0
.
或两位数:
scale_y_continuous(labels = scales::percent_format(accuracy = 3L))
有一个几乎重复的问题.在此处查看Henrik的答案:如何防止小数位数::百分比加小数
There is a near-duplicate question. Check Henrik's answer here: How to prevent scales::percent from adding decimal
这篇关于如何在ggplot2中将百分比四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!