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"))
Hey, thanks for the example, it helped me figure out what I was doing here. Just one minor booboo, your second examples should be ‘values=c(“blue…’ in scale_colour_manual.
very good help, thanks!!
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.
?. 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.
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?
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
Pingback: Plot a function with ggplot, equivalent of curve() - PhotoLens
Pingback: Plot a function with ggplot, equivalent of curve() – Row Coding