Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
In principle, you can pass any reformatting function to the labels
parameter:
+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %
Or
+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign
Reproducible example:
library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
ggplot(df, aes(x,y)) +
geom_point() +
scale_y_continuous(labels = function(x) paste0(x*100, "%"))
ggplot2
and scales
packages can do that:
y <- c(12, 20)/100
x <- c(1, 2)
library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)
It seems like the stat()
option has been taken off, causing the error message. Try this:
library(scales)
myplot <- ggplot(mtcars, aes(factor(cyl))) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels=percent)
myplot
Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With