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

Joh*_* J. 5 r ggplot2

我正在制作一系列条形图,其中百分比值位于每个条形图上方.我想把它舍入到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)
Run Code Online (Sandbox Code Playgroud)

这给你:在此输入图像描述

有没有办法将它们舍入到最接近的整数,这样条形标记为47%,38%和16%?

解决方法可能包括手动注释标签或生成摘要data.frame,从中拉出标签.但是,由于我生成了大量的表,我更倾向于在单个ggplot命令中包含我的所有代码.

Bis*_*est 8

这是对您当前代码的最小更改,它将执行您想要的操作:

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)
Run Code Online (Sandbox Code Playgroud)

我已经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
Run Code Online (Sandbox Code Playgroud)

当我必须在6个月内回顾并查看它时,弄清楚我做了什么将会容易得多.


Ben*_*amp 5

我处理了同样的问题,并通过添加解决它accuracy = 1Lscales::percent()它完美地工作:

label = scales::percent(round((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..], 
                              2), 
                        accuracy = 1L))
Run Code Online (Sandbox Code Playgroud)

  • 显然 `scales::percent()` 已经退役了。对此答案的更新是“scales::label_percent(accuracy = 1L)” (2认同)