77

Is there an equivalent method for plotting functions using ggplot to the curve() command employed in base graphics? I guess that the alternative would be to just create a vector of values of the function and plot a connected line, but I was hoping for something a bit more simple.

Thanks!

Henrik
  • 65,555
  • 14
  • 143
  • 159
Charlie
  • 2,801
  • 3
  • 26
  • 27

2 Answers2

87

You can add a curve using the stat_function:

ggplot(data.frame(x=c(0, 10)), aes(x)) + stat_function(fun=sin)

If your curve function is more complicated, then use a lambda function. For example,

ggplot(data.frame(x=c(0, 10)), aes(x)) + 
  stat_function(fun=function(x) sin(x) + log(x))

you can find other examples at http://kohske.wordpress.com/2010/12/25/draw-function-without-data-in-ggplot2/


In earlier versions, you could use qplot, as below, but this is now deprecated.

qplot(c(0,2), fun=sin, stat="function", geom="line")
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
kohske
  • 65,572
  • 8
  • 165
  • 155
  • 7
    For `qplot(c(0,2), fun=sin, stat="function", geom="line")`, `stat` is deprecated now in 2016 and `fun` is no longer an acceptable parameter. – akhmed Mar 21 '16 at 02:38
2

The data.frame example above works well, and it makes grid lines. The qplot example doesn't work in ggplot2 2.2.0 for the reasons given.

You can also use the "curve" function in ggplot2 2.2.0, but it does not automatically make grid lines or background color. For example:

curve(cos(x), from= 0, to= pi/2).  

The "ggplot(data.frame(... ) method gives the full impressive range of ggplot2's formatting options. I like it.

OTStats
  • 1,820
  • 1
  • 13
  • 22
  • 4
    `curve` is a base function, not a ggplot2 function. The reason it doesn't make grid lines or background color like `ggplot2` is because it's not `ggplot2`. – Gregor Thomas Jan 22 '20 at 03:42