7

I want to produce a bar plot, similar to this MWE:

library(tidyverse)
library(ggplot2)

mtcars %>% 
  mutate(mpg=mpg/1000) %>% 
  ggplot(aes(x=cyl, y=mpg)) +
  geom_bar(stat="identity") +
  scale_y_continuous(labels = scales::percent)

What I get is the following (keep in mind that it is nonsense, but serves illustration purposes): enter image description here Now, I want the decimals replaced from the percentages on the y-axis ("30%" instead of "30.0%"). What can I do?

I have found a similar question here, but couldn't make the function NRPercent does not work (and can't comment there).

Lukas
  • 424
  • 3
  • 6
  • 17
  • 1
    See the question linked to as a possible duplicate, but also look at `?scales::percent`. The function you're using for labeling multiplies values by 100 and tacks on a percent sign, so a number like 0.0125 will come out as 1.25% by default. There's an argument for setting the accuracy to drop the decimals. – camille Sep 05 '18 at 14:16

2 Answers2

24

With the new version of scales you can use:

scale_y_continuous(labels = scales::percent_format(accuracy = 1))
Axeman
  • 32,068
  • 8
  • 81
  • 94
2

Here is a post that would help out : How do I change the number of decimal places on axis labels in ggplot2?

I posted the solution here just so you have it here. Added percent sign to values.

mtcars %>% 
  mutate(mpg=mpg/1000) %>% 
  ggplot(aes(x=cyl, y=mpg*100)) +
  geom_bar(stat="identity") +
  scale_y_continuous("Percent", labels = function(x) paste0(sprintf("%.0f", x),"%"))
Axeman
  • 32,068
  • 8
  • 81
  • 94
Mike
  • 3,797
  • 1
  • 11
  • 30