提问人:John J. 提问时间:12/15/2016 更新时间:12/24/2021 访问量:42374
在geom_text中,“labels=scales::p ercent”可以四舍五入吗?
In geom_text, can "labels=scales::percent" be rounded?
问:
我正在制作一系列条形图,其中百分比值位于每个条形的上方。我想将其四舍五入到小数点后 0 位,但它默认为小数点后 1 位。下面是一个使用 mtcars 的示例。
library(ggplot2)
library(scales)
d <- mtcars
g <- ggplot(d, aes(gear)) +
geom_bar(aes(y = (..count..)/sum(..count..), fill=factor(..x..)), stat= "count")+
geom_text(aes(label = scales::percent((..count..)/sum(..count..)),
y= ((..count..)/sum(..count..))), stat="count",
vjust = -.25)
有没有办法将它们四舍五入到最接近的整数,以便将条形标记为 47%、38% 和 16%?
解决方法可能包括手动批注标签或生成汇总的 data.frame,从中提取标签。但是,由于我正在生成大量表,因此我更愿意将所有代码包含在单个 ggplot 命令中。
答:
20赞
Bishops_Guest
12/15/2016
#1
下面是对当前代码的最小更改,它将执行所需的操作:
library(ggplot2)
library(scales)
d <- mtcars
g <- ggplot(d, aes(gear)) +
geom_bar(aes(y = (..count..)/sum(..count..), fill=factor(..x..)), stat= "count")+
geom_text(aes(label = scales::percent(round((..count..)/sum(..count..),2)),
y= ((..count..)/sum(..count..))), stat="count",
vjust = -.25)
我在您的部门中添加了一个调用,该调用将在将比率传递给 之前将比率四舍五入。round(...,2)
percent
就个人而言,为了代码的清晰性,我会在 ggplot 之外执行此操作。
library(ggplot2)
library(scales)
library(dplyr)
d <- mtcars %>%
group_by(gear) %>%
summarise(Count = n()) %>%
mutate( gear = factor(gear),
Ratio = Count / sum(Count),
label = percent(Ratio %>% round(2)))
g <- ggplot(d, aes(x=gear,y=Ratio,label=label,fill=gear)) +
geom_bar(stat='identity') +
geom_text(vjust=0)
g
当我必须在 6 个月后回头看时,弄清楚我做了什么会容易得多。
8赞
Benjamin Telkamp
6/13/2019
#2
我处理了同样的问题并通过添加解决了它,它运行良好:accuracy = 1L
scales::percent()
label = scales::percent(round((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..],
2),
accuracy = 1L))
评论
4赞
nniloc
5/8/2020
显然已经退休了。此答案的更新是scales::percent()
scales::label_percent(accuracy = 1L)
0赞
BLT
10/7/2023
问题是它不需要数据参数。scales::label_percent()
0赞
Julien
10/14/2023
@nniloc似乎有效,但并非如此percent
label_percent
评论