gpt4 book ai didi

r - 在geom_text中, "labels=scales::percent"可以四舍五入吗?

转载 作者:行者123 更新时间:2023-12-02 01:26:02 25 4
gpt4 key购买 nike

我正在制作一系列条形图,其中百分比值位于每个条形上方。我想将其四舍五入到小数点后 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)

这将为您提供:enter image description here

有没有办法将这些四舍五入到最接近的整数,以便将条形图标记为 47%、38% 和 16%?

解决方法可能包括手动注释标签或生成汇总的 data.frame 以从中提取标签。但是,由于我要生成大量表格,因此我更愿意将所有代码包含在单个 ggplot 命令中。

最佳答案

以下是对当前代码的最小更改,可以实现您想要的功能:

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 个月后回头看时,就会更容易弄清楚我做了什么。

关于r - 在geom_text中, "labels=scales::percent"可以四舍五入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com