ben
ben

Reputation: 799

R geom_ribbon not shading area under density curve properly over interval

I am trying to shade the area under a lognormal density plot for a certain interval using the code below. This has worked for me in the past using other density functions and intervals, but for some reason now it produces the defect you can see in the graphic.

fig 1

library(ggplot2)
library(plyr)
library(dplyr)
library(tidyr)

x <- seq(0, 43, 0.1)

x_min <- 16
x_max <- 22
df <- data.frame(x = x, f = dlnorm(x, meanlog = 2.5,
                                     sdlog = 0.24))
df <- df %>% mutate(area = ifelse(x >= x_min & x < x_max,
                                      "Participating", "Not Participating"))
gg <- ggplot(data = df, aes(x = x, ymin = 0, ymax = f, fill = area))
gg <- gg + geom_ribbon()
gg <- gg + theme(legend.title = element_blank())
gg

Upvotes: 1

Views: 795

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48221

The issue here is that you are trying to have a ribbon consisting of two pieces. Consequently, the two intended red areas try to connect to each other: ymax where the left area ends and ymax where the right one starts, and the same for ymin. Probably in the past you always used this method for the distribution tails and this problem never arose.

As to solve this, you are going to need to somehow manually have two geom_ribbon. A not particularly intrusive way would be

gg <- ggplot(data = df, aes(x = x, ymin = 0, ymax = f))
gg <- gg + geom_ribbon(aes(fill = factor("Not participating")))
gg <- gg + geom_ribbon(data = df[df$area == "Participating", ], aes(fill = area))
gg <- gg + theme(legend.title = element_blank())

enter image description here

Depending on that you wish to do with colors, it potentially can be further modified/simplified.

Upvotes: 1

Related Questions