Niko24
Niko24

Reputation: 81

Plot a function in R

I need to plot the following function in R:

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

So far I've tried the following:

fx1 = function(x){
  2+0.4*x
}
fx2 = function(x){
  -2-0.6*x
}
plot(fx1, -10,  0)
plot(fx2,   0, 10)

But the functions are plotted in two different windows. I've also tried to add: add=TRUE to the second plot, which I read on Stack Overflow, but this didn't help me either.

Upvotes: 1

Views: 152

Answers (1)

Bernhard
Bernhard

Reputation: 4427

To plot functions, use curve. Use plot, to get the coordinates before adding curves:

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)

Edit: For better definition at x=0, may I suggest

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)

Upvotes: 1

Related Questions