how to use a group variable as an argument for stat_function

瀏覽次數:22 次
跳到第一則未讀訊息

Boylan, Ross

未讀,
2017年9月29日 下午2:39:352017/9/29
收件者:ggplot
I have a column in my data.frame that I want to use as a grouping variable and also as an argument to the function I hand to stat_function. But I can't figure out how to capture it for that function. The goal is plot a function from -3 to 3 with 3 different values for the parameter theCut.

> agrid
eta cut
1 -3 5
2 3 5
3 -3 14
4 3 14
5 -3 88
6 3 88
> ggplot(agrid, aes(x=eta, colour=cut))+stat_function(fun=eta_exceed, args=list(theCut=cut))
Error in pnbinom(q, size, prob, lower.tail, log.p) (from negbin.R#7) :
Non-numeric argument to mathematical function
# debugging shows theCut argument to eta_exceed is
#function (x, ...)
#UseMethod("cut")
#<bytecode: 0x1b4d270>
#<environment: namespace:base>

# So rename to avoid collisions
> colnames(agrid) <- c("eta", "xcut")
> ggplot(agrid, aes(x=eta, colour=xcut))+stat_function(fun=eta_exceed, args=list(theCut=xcut))
Error in do.call("layer", list(mapping = mapping, data = data, geom = geom, :
object 'xcut' not found

I got my plot by constructing a data.frame with all the intermediate points and evaluating my target function for each, then doing a regular plot with grouping. But I suspect there's a better way.

Suggestions?

For reference:
eta_exceed <- function(eta, theCut=14, theSize=0.7){
meanY <- exp(eta)
p <- theSize/(meanY+theSize)
pnbinom(theCut, theSize, p, lower.tail=FALSE)
}

ggplot2 0.8.9 in R 2.15.1.
回覆所有人
回覆作者
轉寄
0 則新訊息