how to use a group variable as an argument for stat_function

22 views
Skip to first unread message

Boylan, Ross

unread,
Sep 29, 2017, 2:39:35 PM9/29/17
to 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.
Reply all
Reply to author
Forward
0 new messages