xshbj
xshbj

Reputation: 93

r ggplot2: fill area under curves with geom_step

I'm trying to fill area under each step function using ggplot2 and geom_step. Here's an example dataset:

time = c(0, 5, 8, 11, 14, 18, 20, 0, 3, 7, 13, 19, 20, 0, 4, 9, 15, 18)
prob = c(1, 0.95, 0.80, 0.62, 0.30, 0.03, 0, 1, 0.92, 0.75, 0.57, 0.21, 0, 1, 0.80, 0.64, 0.43, 0)
group = c(1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3)

df = data.frame(time, prob, group)

Here's the codes i've tried:

plot1 = ggplot(df, aes(x = time, y = prob, group = group, fill = group)) +
geom_step()+
geom_ribbon(data = df, aes(ymin = 0, ymax = prob))

The problem is that, after fill the area, only group 1 has the step line, and the area filling is not following the step function.

Upvotes: 1

Views: 1464

Answers (1)

Kra.P
Kra.P

Reputation: 15143

You may use geom_rect instead of geom_ribbon.

df %>%
  mutate(group = as.factor(group)) %>%
  ggplot(aes(x = time, y = prob, group = group, fill = group)) +
  geom_step()+
  geom_rect(aes(xmin = time, xmax = lead(time), 
                ymin = 0, ymax = prob), alpha = 0.4)

enter image description here

Upvotes: 5

Related Questions