SpinningAtInfinity - 1 year ago 82

R Question

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)`

and

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

What could I do to plot such function?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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)
```

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)")
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**