当x轴是离散的时,geom_ribbon覆盖

Dre*_*een 4 r ggplot2

我想在一组箱图上加一个底层来表示从一个单独的数据源和一个单独的数据框中提取的一些数据的范围.制作的叠加是容易的; 制作衬底很难.

想象一下,出于这些目的,我试图将一些数据从mtcars一个diamonds数据箱图中得到:

# Find quantiles of mtcars$drat
mQ <- quantile(mtcars$wt, c(0.025, 0.975))

# Place them in a data frame with factor limits of diamonds$cut
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))

# Plot diamonds$cut, with overlay of quantiles from mtcars
ggplot() + 
  geom_boxplot(data=diamonds, aes(x=cut, y=y)) +
  geom_ribbon(data=mtcarsQ, aes(x=x, ymin=ymin, ymax=ymax), alpha=0.2)+
  coord_cartesian(ylim=c(0, 12))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这很好 - 除了我(实际上:我的共同作者)想要在geom_ribbon谎言下面而不是箱形图上.(据称色带的颜色会干扰盒子图的颜色).当我试图颠倒geoms的顺序时:

ggplot() + 
  geom_ribbon(data=mtcarsQ, aes(x=x, ymin=ymin, ymax=ymax), alpha=0.2)+
  geom_boxplot(data=diamonds, aes(x=cut, y=y))
Run Code Online (Sandbox Code Playgroud)

我知道Error: Discrete value supplied to continuous scale,因为ggplot不想将因子映射到连续的比例.

我可以尝试使因子数字:

ggplot() + 
  geom_ribbon(data=mtcarsQ, aes(x=x, ymin=ymin, ymax=ymax), alpha=0.2)+
  geom_boxplot(data=diamonds, aes(x=as.numeric(cut), y=y))
Run Code Online (Sandbox Code Playgroud)

但是,这会更改x轴标签.我原本以为我可以按如下方式添加轴标签:

ggplot() + 
  geom_ribbon(data=mtcarsQ, aes(x=x, ymin=ymin, ymax=ymax), alpha=0.2)+
  geom_boxplot(data=diamonds, aes(x=as.numeric(cut), y=y, fill=cut, group=cut)) +
  scale_x_discrete(labels=levels(diamonds$cut)) +
  coord_cartesian(ylim=c(0, 12))
Run Code Online (Sandbox Code Playgroud)

但由于我不理解的原因,x轴出现了额外的因子水平.

在此输入图像描述

当箱形图具有离散的x轴时,是否有更简单的方法将矩形放在箱线图下方?

Dre*_*een 7

强制缩放以您希望的方式强制缩放的最常用方法是开始geom_blank,这将定义缩放但不绘制任何内容.我相信它是针对这种情况而设计的:

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述