在R中绘制函数

在R中绘制函数,r,ggplot2,data-visualization,R,Ggplot2,Data Visualization,我需要在R中绘制以下函数: M(x) = 2 + 0.4x {when x <= 0} -2 + 0.6x {when x > 0} 但函数是在两个不同的窗口中绘制的。我还尝试将:add=TRUE添加到第二个图中,这是我在堆栈溢出时读到的,但这也没有帮助我 要绘制函数,请使用曲线。使用绘图,在添加曲线之前获取坐标: fx1 = function(x){ 2+0.4*x } fx2 = function(x){ -2-0.6*x } plot(NA, xl

我需要在R中绘制以下函数:

M(x) =  2 + 0.4x {when x <= 0} 
       -2 + 0.6x {when x >  0}

但函数是在两个不同的窗口中绘制的。我还尝试将:
add=TRUE
添加到第二个图中,这是我在堆栈溢出时读到的,但这也没有帮助我

要绘制函数,请使用
曲线
。使用
绘图
,在添加曲线之前获取坐标:

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)

每次调用plot,都会得到一个新窗口。将绘图(fx2…)替换为线条(fx2…),然后将线条粘贴到已打开的同一绘图中。查看此链接了解有关绘图的更多信息:如果我使用直线,我会得到以下错误:as.double(x)中的错误:无法将类型“closure”强制为类型“double”的向量,但是我得到了add=TRUE,但您知道如何正确定义间隔,它仅使用第一个绘图的间隔。
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)