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

时间:2013-05-07 03:57:17

标签: 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))

enter image description here

这很好 - 除了我(实际上:我的合着者)希望{/ 1}}谎言下而不是 over 箱图。 (据称色带的颜色会干扰盒子图的颜色)。当我试图扭转像这样的geoms的顺序时:

geom_ribbon

我得到ggplot() + geom_ribbon(data=mtcarsQ, aes(x=x, ymin=ymin, ymax=ymax), alpha=0.2)+ geom_boxplot(data=diamonds, aes(x=cut, y=y)) ,因为ggplot不想将因子映射到连续比例。

我可以尝试将因子数字化:

Error: Discrete value supplied to continuous scale

但是,这会更改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))

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

enter image description here

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

3 个答案:

答案 0 :(得分:5)

强制缩放以您希望的方式默认缩放的最常用方法是从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))

enter image description here

答案 1 :(得分:3)

第二次应用箱线图:

ggplot() + 
geom_boxplot(data=diamonds, aes(x=cut, y=y, fill=cut, group=cut)) +
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))

enter image description here

答案 2 :(得分:3)

如果您使用scale_x_continuous()然后不仅提供labels=而且还提供breaks=,那么将因子值设为数字的解决方案将有效。

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_continuous(breaks=1:5,labels=levels(diamonds$cut)) +
  coord_cartesian(ylim=c(0, 12))

enter image description here