In geom_text, can "labels=scales::percent" be rounded?

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)

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


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

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.


I dealt with the same problem and solved it by adding accuracy = 1L in scales::percent() and it worked perfectly:

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

Tags:

R

Ggplot2