在geom_text中,可以"labels = scales :: percent"被舍入? [英] In geom_text, can "labels=scales::percent" be rounded?

查看:137
本文介绍了在geom_text中,可以"labels = scales :: percent"被舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一系列条形图,其中百分比值位于每个条形上方.我想将其舍入到小数点后0位,但默认为1小数点后一位.这是使用mtcars的示例.

I'm making a series of bar charts where the percent value is placed above each bar. I'd like to round this to 0 decimal places, but it defaults to 1 decimal place. Here's an example using 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%?

Is there a way to round these to the nearest whole number, so that the bars are labeled 47%, 38%, and 16%?

解决方法可以包括手动注释标签或生成摘要的data.frame以从中拉标签.但是,由于要生成大量表,因此我更希望将所有代码都包含在单个ggplot命令中.

Work-arounds could include annotating the labels manually or generating a summarized data.frame from which to pull the labels. However, since I'm generating numerous tables, I'd much prefer to include all of my code within the single ggplot command.

推荐答案

这是对当前代码的最小更改,可以完成您想要的操作:

here is the a minimal change to your current code that will do what you want:

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之前对其进行四舍五入.

I have added a call to round(...,2) in your division that will round the ratio before passing it to percent.

就个人而言,我会在ggplot之外执行此操作,以使代码清晰明了.

Personally, I would do this outside of ggplot for clarity of code.

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个月内的情况时,弄清楚我做了什么会容易得多.

When I have to go back and look at that in 6 months, it will be a lot easier to figure out what I did.

这篇关于在geom_text中,可以"labels = scales :: percent"被舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆