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"))


6 thoughts on “Draw function without data in ggplot2

  1. Nice, but how would you fille the area under the curve from -2 to 0.
    I mean with the same method, without explicitly generating pairs of points before.

  2. ?. If I try ggplot(data.frame(x=c(-2, 2)),aes(x)) + stat_function(fun=dnorm)+ geom_area(aes(xlim=c(-2,0)),stat=”function”, fun=dnorm)
    I get all the area under the curve fiiled instead of the region I want
    Other options such as geom=”ribbon” or fill=”red” don’t work either.

  3. ggplot(NULL,aes(x=c(-2,2))) + geom_area(aes(x=c(-2,0)),stat=”function”, fun=dnorm, fill=”red”) + geom_area(aes(x=c(0,2)),stat=”function”, fun=dnorm, fill=”blue”) doesn’t paint with two colours. How can I get it?

  4. I get an error message running your code:
    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”))
    Error: Breaks and labels have unequal lengths

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s