Reputation: 1499
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
?
Upvotes: 1
Views: 144
Reputation: 77116
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)
Upvotes: 2