我对scales::percent
不满意,例如,scales::percent(21/80)
返回“26.2%”,而我更喜欢“26.25%”。所以我写了一个快速的功能:
custom_percent <- function(x, digits = 2) {
paste0(round(100 * x, digits = digits), "%")
}
但是,当我尝试将它与ggplot2一起使用时,我收到以下错误"Error in eval(expr, envir, enclos) : could not find function "custom_percent"
。这是一个例子:
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)
如何访问custom_percent
?
答案 0 :(得分:2)
aes_q
和bquote
can help这些棘手的范围问题,
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)