I'm not happy with scales::percent, for example, scales::percent(21/80) returns "26.2%" while I'd prefer getting "26.25%". So I wrote a quick function:
custom_percent <- function(x, digits = 2) {
paste0(round(100 * x, digits = digits), "%")
}
However, when I try to use it with ggplot2, I receive the following error "Error in eval(expr, envir, enclos) : could not find function "custom_percent". Here is an example:
dset <- data.frame(data = 10:90)
p <- ggplot(dset, aes(x = data))
p + geom_bar(aes(y = (..count..)/sum(..count..)), width = .5) +
geom_text(aes(y = ((..count..)/sum(..count..)),
label = custom_percent((..count..)/sum(..count..))),
stat = "count", vjust = -0.25) +
scale_y_continuous(labels = custom_percent)
What can I do to access custom_percent?
ggplotnot being able to find the custom function. For example,d <- data.frame(x=1:10, y=rnorm(10))and thenggplot(d) + geom_text(aes(x, y, label = custom_percent(y)))works perfectly fine...count..) together with a custom function. Interesting.scales::percenteverywhere instead, it just worked. But thenscaleswas by the same author who wroteggplot2so maybe he used a trick in both.aes, that was the first path I tried. And of course it miserably failed. Maybe because, in my case, theggplotandaescalls were not inside a function definition.