Francisco
Francisco

Reputation: 189

area between step-wise functions in R

I would like to draw the area between two step wise functions.

I have try geom_ribbon, but I get the draw with interpolations rather than constant in intervals.

comb = data.frame(time=rexp(20),n1=rep(1:10,each=2),n2=seq(from=2, to=11.5,by=0.5))
ggplot(comb) + geom_ribbon(aes(x=cumsum(time), ymin=n1, ymax=n2), fill="blue", alpha=.4) + geom_step(aes(x=cumsum(time), y=n1))+ geom_step(aes(x=cumsum(time), y=n2))

Any help is appreciated.

Upvotes: 2

Views: 2217

Answers (1)

Brian
Brian

Reputation: 8295

A simple fix is to move your cumsum(time) into your comb dataframe:

comb$ctime <- cumsum(comb$time)

then you can use geom_rect() as follows:

ggplot() + 
  geom_rect(aes(xmin = ctime, xmax = dplyr::lead(ctime), 
                ymin = n1, ymax = n2), 
            fill = "blue", alpha = 0.4) +
  geom_step(aes(x=ctime, y=n1))+ 
  geom_step(aes(x=ctime, y=n2))

Which yields:

enter image description here

Upvotes: 4

Related Questions