green diod green diod - 1 month ago 7
R Question

R ggplot2 doesn't know a custom function

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
?

Answer

aes_q and bquote can help with these tricky scoping issues,

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 = bquote(.(custom_percent)((..count..)/sum(..count..)))),
            stat = "count", vjust = -0.25) +
  scale_y_continuous(labels = custom_percent)
Comments