SpinningAtInfinity SpinningAtInfinity - 10 days ago 4x
R Question

Plot a two step function

I'm trying to plot two curves in the same graph, but it doesn't work. I want to plot the function f(x) = 3x + 2 if x<=3 and f(x) = 2x-0.5x^2 if x>3 on the interval [0,6]. I thought I had to do

curve(3*x+2, 0,3)


curve(2*x-0.5*x^2,3,6, add = TRUE)

What could I do to plot such function?


Use xlim and ylim in the first curve to set the limits of the plot.

curve(3*x+2, 0,3, xlim = c(0, 6), ylim = c(-5, 12))
curve(2*x-0.5*x^2,3,6, add = TRUE)

enter image description here

As the second curve still gets cut off a little bit, you might want to use c(-7 12) for the y limits.

Another option, if you want the lines connected and which removes the need to set manual limits is to encode both functions in one with ifelse:

curve(ifelse(x <= 3, 3 * x + 2, 2 * x - 0.5 * x^2), 0, 6, ylab = "f(x)")

enter image description here