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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.