2017-12-18 544 views
0

我有一些数据,我想使用stat_count()中的一些变量来标记条形图。如何使用自定义函数更改geom_text中的文本标签

这就是我想做的事:

library(ggplot2) 
library(scales) 
percent_and_count <- function(pct, cnt){ 
    paste0(percent(pct), ' (', cnt, ')') 
} 

ggplot(aes(x=Type)) + 
stat_count(aes(y=(..prop))) + 
geom_text(aes(y=(..prop..), label=percent_and_count(..prop.., ..count))), 
    stat='count') 

不过,我得到这个错误,因为它不能在我以为是什么或者是一些基本的包或数据帧寻找功能:

中的eval错误(表达式,ENVIR,enclos):找不到功能 “percent_and_count”

,如果我做percent(..prop..)以及我得到这个错误,althoug h可以用scales::percent(..prop..)。我没有从包中加载我的功能。

如果一切都失败了,我可以做

geom_text(aes(y=(..prop..), label=utils::getAnywhere('percent_and_count')$objs[[1]]((..prop..),(..count..)))) 

但这似乎不必要的迂回什么应该是一个太简单的任务。

回答

1

您可以使用bquoteaes_

# Sample data 
set.seed(2017); 
df <- data.frame(
    Type = sample(6, 100, replace = T) 
); 

library(ggplot2); 
library(scales); 

# Your custom function 
percent_and_count <- function(pct, cnt){ 
    paste0(percent(pct), ' (', cnt, ')') 
} 

ggplot(df, aes(x = Type)) + 
stat_count(aes(y = ..prop..)) + 
geom_text(
    stat = "count", 
    aes_(
     y = ~(..prop..), 
     label = bquote(.(percent_and_count)((..prop..), (..count..))))) 

enter image description here

说明:bquote(.(percent_and_count)(...))确保percent_and_count被找到(如术语.(...)在父环境评估)。然后我们使用aes_来确保引用的表达式(使用~bquote)得到正确评估。

还不算漂亮,但可能比使用utils::getAnywhere更直接。

相关问题