Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a discrete (or discontinuous) function in ggplot2

Tags:

r

ggplot2

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?

like image 453
Gerrit Jan Avatar asked Aug 02 '26 06:08

Gerrit Jan


1 Answers

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")
like image 103
Vincent Zoonekynd Avatar answered Aug 03 '26 21:08

Vincent Zoonekynd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!