使用 ggplot 绘制一个函数,相当于曲线()

是否有一种等效的方法来绘制使用 ggplot的函数到 curve()命令在基础图形中使用?我猜另一种方法就是创建函数值的向量并绘制一条连接线,但我希望能有更简单的方法。

谢谢!

34235 次浏览

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

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.