我需要在R中绘制以下函数:
M(x) = 2 + 0.4x {when x <= 0}
-2 + 0.6x {when x > 0}
到目前为止,我已尝试过以下方法:
fx1 = function(x){
2+0.4*x
}
fx2 = function(x){
-2-0.6*x
}
plot(fx1, -10, 0)
plot(fx2, 0, 10)
但功能在两个不同的窗口中绘制。我还试图将add=TRUE
添加到第二个图中,我在Stack Overflow上读到了这个图,但这对我也没有帮助。
答案 0 :(得分:1)
要绘制函数,请使用curve
。使用plot
,在添加曲线之前获取坐标:
fx1 = function(x){
2+0.4*x
}
fx2 = function(x){
-2-0.6*x
}
plot(NA, xlim=c(-10,10), ylim=c(-10,10))
curve(fx1, from = -10, to = 0, add=TRUE)
curve(fx2, from = 0, to = 10, add=TRUE)
修改强> 为了在x = 0时更好地定义,我可以建议
fx1 = function(x) 2+0.4*x
fx2 = function(x) -2-0.6*x
plot(NA, xlim=c(-10,10), ylim=c(-10,5), ylab="value")
curve(fx1, from = -10, to = 0, add=TRUE)
curve(fx2, from = 0, to = 10, add=TRUE)
points(0, fx1(0), pch=15)
points(0, fx2(0), pch=22)