功能绘图在r

时间:2017-04-24 20:07:10

标签: r statistics

x<-seq(-2*pi,2*pi) #range of x
f<-(2*(abs(sin(x)))+(1/2))
f1<-function(x)(2*(abs(sin(x)))+(1/2))

x1=seq(-2*pi,-pi)
g<-2*cos(x1)
gun<- function(y) 2*cos(x1)
curve(gun, from=-2*pi, to=-pi, type='l')

所以,我想在同一个图中绘制这些函数,但是当我尝试绘制g时出现错误:

Error in curve(gun, from = -2 * pi, to = -pi, type = "l") : 
'expr' did not evaluate to an object of length 'n'

我不知道如何解决这个问题,我看到人们使用Vectorize(),但它似乎没有帮助。 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您正在调用函数中存储在环境中的数据。它应该引用传递给它的数据。

x<-seq(-2*pi,2*pi) #range of x
f<-(2*(abs(sin(x)))+(1/2))
f1<-function(x)(2*(abs(sin(x)))+(1/2))

g<-2*cos(x1)
gun<- function(y) 2*cos(y)
curve(gun, from=-2*pi, to=2*pi, type='l')

enter image description here

将第二个函数添加到绘图中,您可以运行此

curve(f1, from = -2*pi, to = 2*pi, type = 'l', col = "red", add = TRUE)

enter image description here