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()
我想将我的geom_ribbon()
从上面的代码块沿x轴的任一方向扩展。类似于下面的图片。我偏爱的geom_ribbon()
将完全吸引到蓝色虚线框中。
我该怎么做?
答案 0 :(得分:1)
您可以从mtcarsQ$x
减去/加0.5
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()
为回应您的评论,这是一个示例
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")