Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: Fill small area under normal curve: remove "joining" area

Tags:

r

ggplot2

fill

area

I would like to fille a small area under a curve. However, the ribbon geoms join the two "parts" of the distribution.

library(tidyverse)
density(rnorm(1000, 0, 1)) %$%
  data.frame(x=x, y=y) %>%
  mutate(area = dplyr::between(x, 1.5, 2.6)) %>%
  ggplot() +
  geom_ribbon(aes(x = x, ymin = 0, ymax = y, fill = area))

enter image description here

I believe one of the way of avoiding this behaviour would be to split the distribution into three different parts, and fill the two of them with the same colour. However, I am looking for a more neat and elegant way.

like image 873
Dominique Makowski Avatar asked Mar 07 '23 06:03

Dominique Makowski


1 Answers

The problem is the way the red ribbon gets interpolated across the blue region, where there are no red values so a straight line is drawn to the next red point. You can work around this by just plotting the whole ribbon first, not accounting for area, and then plotting the subset over the top:

library(tidyverse)
density(rnorm(1000, 0, 1)) %$%
    data.frame(x=x, y=y) %>%
    mutate(area = dplyr::between(x, 1.5, 2.6)) %>%
    ggplot(aes(x = x, ymin = 0, ymax = y)) +
    geom_ribbon(aes(fill = "Outside")) +
    geom_ribbon(aes(fill = "Inside"), data = function(df) df %>% filter(area))

Result:

enter image description here

like image 125
Marius Avatar answered Mar 24 '23 01:03

Marius