[英]error when using custom function in ggplot2::stat_summary()
[英]ggplot2: stat_summary throws error when trying to pass function argument as parameter, rather than hard-coding
當我嘗試將參數傳遞給stat_summary
的round
函數時,我收到錯誤(即使類似的代碼與geom_text
)。 這是一個例子:
# Fake data
set.seed(5)
dat = data.frame(group=rep(c("A","B"),each=10), val=rnorm(20))
我們將嘗試使用參數設置值標簽的小數位數,而不是硬編碼:
places = 2
ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places)))
eval中的錯誤(expr,envir,enclos):找不到對象'places'
但是,以下兩個示例工作正常。
ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., 2)))
ggplot(dat, aes(group, val)) +
geom_text(aes(label=round(val, places)))
我在嘗試編寫ggplot函數時遇到了這個問題。 起初我認為問題涉及ggplot沒有從函數環境中獲取參數,但上面的例子表明這不是問題。 為了完整起見,下面是該函數的簡化示例以及錯誤消息。 如果我將數字參數硬編碼為round
,而不是嘗試傳遞places
參數,則該函數可以正常工作。
pp1 = function(data, group, var, places=2, e=1.5) {
ggplot(data, aes_string(group, var)) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places))) +
scale_y_continuous(limits = e * range(data[,var]))
}
pp1(dat, "group","val")
eval中的錯誤(expr,envir,enclos):找不到對象'places'
我希望了解我是否做錯了什么以及我如何能夠獲得理想的行為。
我在OS X ggplot2
上運行R
3.2.3和ggplot2
2.1.0。
aes
使用非標准的評價 ,因此將嘗試評估places
的范圍內data
,你給它的參數。 但它的NSE會有所不同,具體取決於你傳遞的內容。
繞過NSE的典型方法是使用substitute
,它可以替代代碼中的值。 然后,您可以使用eval
運行代碼:
eval(substitute(ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places))),
list(places = places)))
它按預期工作:
Hadley還提供了幾個SE版本的aes
: aes_
, aes_q
和aes_string
,它們可以讓你避免使用substitute
,但是我無法評估..y..
(如果有人知道如何構建它,請評論,我會更新。)
Hadley還創建了lazyeval包 ,這對管理NSE非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.