using stat_function() to produce simple plots

18 views
Skip to first unread message

russ

unread,
Feb 7, 2009, 7:44:59 PM2/7/09
to ggplot2
Hi,

First, terrific tool.

I am just starting to learn ggplot2 and grid graphics.
I am wondering if it is possible to directly plot a function without
the initial plot?

something along the lines of:

x<-seq(-3,3,.01)
ggplot() + stat_function(fun = dnorm,args=list(x=x,m=0,sd=1))

It appears that data is essential to create the plot. Putting x in a
data.frame doesnot help either.
I am sure I am missing the point here.

Thanks in advance,

russ

hadley wickham

unread,
Feb 7, 2009, 10:11:42 PM2/7/09
to russ, ggplot2
Hi Russ,

I'd never really thought about using stat_function for that purpose -
it's basically designed to work with on top of an existing plot.
However, it's pretty easy to make a little function to do what you
want:

fplot <- function(f, .min, .max, ..., .n = 100) {
x <- seq(.min, .max, length = .n)
y <- f(x, ...)

qplot(x, y, data = data.frame(x, y), geom = "line")
}

fplot(dnorm, -3, 3, mean = 0, sd = 1)

(I use . in front of min and max so that you don't inadvertently match
those arguments instead of the arguments of the function that your
plotting)

If you wanted to go even further and automatically come up with good
default limits for the plot, you could use the ideas in here:
http://www.cs.uic.edu/~wilkinson/Publications/plotfunc.pdf

Hadley
--
http://had.co.nz/

russ

unread,
Feb 7, 2009, 10:26:38 PM2/7/09
to ggplot2
Thanks for the quick reply.
The intended use of stat_function() makes perfect sense and your
solution is reasonable.
Thanks for the link - I have often wondered about the exact same
issue.

~RT
> --http://had.co.nz/- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages