2017-12-18 545 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更直接。

相關問題