Ggplot2 geom_area ribs not vertical

I am trying to fill in the slices (along the x axis) of the area under the curve in different colors using ggplot geom_area. But for some reason I can’t get the sides of the regions to be vertical. Here's a minimal reproducible example:

library(ggplot2)
x = 1:10
pdat = data.frame(y = log(x), x = x)
ggplot(pdat, aes(x=x, y=y)) +
    geom_area(aes(y = ifelse(y > 2 & y < 5, y, 0)), 
              fill = "red", alpha = 0.5) +
    geom_line()

enter image description here

Thanks for your suggestions!

+4
source share
1 answer

The problem is that for x = 7 the y value is now 0, but for x = 8 the y value is 2.0794415, and therefore the interval between the intervals.

Instead, you can use a subset pdatto geom_area:

ggplot() +
  geom_area(data = pdat[pdat$y > 2 & pdat$y < 5,], aes(x = x, y = y), 
            fill = "red", alpha = 0.5) +
  geom_line(data = pdat, aes(x = x, y = y))

enter image description here

+5
source

Source: https://habr.com/ru/post/1675942/


All Articles