Equivalent to curve () for ggplot

Is there an equivalent method for constructing functions using ggplot with the curve() command used in the base graph? I suggest that an alternative would be to simply create a vector of function values ​​and build a connected line, but I was hoping for something simpler.

Thank!

+48
r ggplot2
Mar 03 '11 at 7:25
source share
2 answers

You can add a curve using stat_function :

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

You can also use qplot , but this is unclear if it is simpler:

 qplot(c(0,2), fun=sin, stat="function", geom="line") 

If your curve function is more complicated, use the 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/

+52
Mar 03 2018-11-11T00:
source share
— -

The example "data.frame" above works well, and it creates grid lines. The qplot example does not work in ggplot2 2.2.0 for the above reasons.

You can also use the curve function in ggplot2 2.2.0, but it does not automatically draw grid lines or background colors. For example: curve (cos (x), from = 0, to = pi / 2).

The ggplot (data.frame (...) method gives a complete impressive range of ggplot2 formatting options. I like it.

+1
Nov 20 '16 at 4:26
source share



All Articles