用ggplot绘制函数,等效于curve() [英] Plot a function with ggplot, equivalent of curve()
问题描述
在基本图形中使用curve()
命令时,是否存在使用ggplot
绘制函数的等效方法?我想,替代方法是只创建函数值的向量并绘制一条连接的线,但是我希望有一些更简单的方法.
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.
谢谢!
推荐答案
您可以使用stat_function
添加曲线:
ggplot(data.frame(x=c(0, 10)), aes(x)) + stat_function(fun=sin)
如果曲线函数更复杂,请使用lambda函数.例如
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))
您可以在以下位置找到其他示例 http://kohske.wordpress.com /2010/12/25/draw-function-without-data-in-ggplot2/
you can find other examples at http://kohske.wordpress.com/2010/12/25/draw-function-without-data-in-ggplot2/
在早期版本中,您可以使用qplot
,如下所示,但现在已弃用.
In earlier versions, you could use qplot
, as below, but this is now deprecated.
qplot(c(0,2), fun=sin, stat="function", geom="line")
这篇关于用ggplot绘制函数,等效于curve()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!