Reputation: 4481
library(tidyverse)
mQ <- quantile(mtcars$wt, c(0.025, 0.975))
mtcarsQ <- data.frame(x = c(min(as.numeric(diamonds$cut)),
max(as.numeric(diamonds$cut))),
ymin = rep(mQ[1], 2),
ymax = rep(mQ[2], 2))
ggplot() +
geom_blank(data = diamonds, aes(x = cut, y = y)) +
geom_ribbon(data = mtcarsQ, aes(x = x, ymin = ymin, ymax = ymax), alpha=0.2) +
geom_boxplot(data = diamonds, aes(x = cut, y = y, fill = cut, group = cut)) +
coord_cartesian(ylim = c(0, 12)) +
theme_bw()
I'd like to extend my geom_ribbon()
from code chunk above in either direction on the x-axis. Something resembling the image below. My preferred geom_ribbon()
would fully entend into the blue dotted line box.
How do I do this?
Upvotes: 2
Views: 1848
Reputation: 50668
You could subtract/add 0.5 from mtcarsQ$x
mtcarsQ <- data.frame(x = c(min(as.numeric(diamonds$cut)) - 0.5,
max(as.numeric(diamonds$cut)) + 0.5),
ymin = rep(mQ[1], 2),
ymax = rep(mQ[2], 2))
ggplot() +
geom_blank(data = diamonds, aes(x = cut, y = y)) +
geom_ribbon(data = mtcarsQ, aes(x = x, ymin = ymin, ymax = ymax), alpha=0.2) +
geom_boxplot(data = diamonds, aes(x = cut, y = y, fill = cut, group = cut)) +
coord_cartesian(ylim = c(0, 12)) +
theme_bw()
In response to your comment, here is an example
mtcars %>%
mutate(cyl = factor(cyl)) %>%
ggplot() +
geom_col(aes(cyl, mpg)) +
geom_rect(
data = data.frame(
xmin = min(as.integer(as.factor(mtcars$cyl))) - 0.5,
xmax = max(as.integer(as.factor(mtcars$cyl))) + 0.5,
ymin = 20,
ymax = 120),
aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
alpha = 0.2, fill = "green")
Upvotes: 2