Draw function without data in ggplot2


Sometimes I need to draw mathematical functions only by specifying the xlim and without read data.
stat_function() can handle this.

 

Basic form is:

qplot(c(0, 2), stat="function", fun=exp, geom="line") 
# or
ggplot(data.frame(x=c(0, 2)), aes(x)) + stat_function(fun=exp)


 

Here is an example to draw two functions on one plot:

ggplot(data.frame(x=c(0,2)), aes(x)) +
  stat_function(fun=function(x)x^2, geom="line", aes(colour="square")) +
  stat_function(fun=exp, geom="line", aes(colour="exp")) +
  scale_colour_manual("Function", value=c("blue","red"), breaks=c("square","exp"))

About these ads

One thought on “Draw function without data in ggplot2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s