user14683403
user14683403

Reputation:

How to plot a piecewise function in R?

I have a function

g(h) = 2h for -20 <= h <= 20 and 1 otherwise.

How can I plot this using R?

Very new to R so thanks for any guidance

Upvotes: 0

Views: 814

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

For a basic plot, it doesn't much matter whether your function is piecewise or not. Make it a function, then plot it. Pick your favorite method from the How to plot a function? FAQ. I show two possibilities below. If you want to avoid the vertical line connecting the pieces, then you'll need to plot each piece independently.

foo = function(x) {
  ifelse(-20 <= x & x <= 20, 2*x, 1)
}

## base plot:
curve(foo, from = -25, to = 25)

## with ggplot
library(ggplot2)
ggplot(data.frame(x = c(-25, 25)), aes(x = x)) +
  stat_function(fun = foo)

enter image description here

enter image description here

Upvotes: 2

Related Questions