I have the following function, which I would like to plot using ggplot:
f(x) = 3/4 for x between 0 and 1; 1/4 for x between 2 and 3; and 0 elsewhere.
I have come up with the following R code:
eq<-function(x) {
if(x>=0 && x<=1) {
y<-3/4
} else if(x>=2 && x<=3) {
y<-1/4
} else {
y<-0
}
return(y)
}
library(ggplot2)
ggplot(data.frame(x=c(-5,5)), aes(x)) + stat_function(fun=eq)
However, this results in a plot with only a horizontal line centered on 0. What have I done wrong?
The function should be "vectorized", i.e., accept a vector as argument.
eq <- function(x)
ifelse( x>=0 & x<=1, 3/4,
ifelse( x>=2 & x<=3, 1/4, 0 ))
ggplot(data.frame(x=c(-5,5)), aes(x)) +
stat_function(fun=eq, geom="step")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With