用ggplot绘制一个函数,相当于curve() [英] Plot a function with ggplot, equivalent of curve()

查看:32
本文介绍了用ggplot绘制一个函数,相当于curve()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ggplot 绘制函数是否有与基本图形中使用的 curve() 命令等效的方法?我想另一种方法是创建函数值的向量并绘制一条连接线,但我希望有一些更简单的东西.

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 添加曲线:

You can add a curve using the 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆