2013-05-07 78 views
2

我想在一組箱形圖上放置一個底層,以指示從單獨的源和單獨的數據框中繪製的一些數據的範圍。製作覆蓋圖很簡單;使襯墊很困難。當x軸離散時,geom_ribbon疊加

試想一下,爲了這些目的,我想從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

這工作得很好 - 除了我(其實是:我共同作者)想要在之下具有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)) 

我得到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)) 

但是,這改變了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)) 

但X軸隆重推出的原因,我不明白額外的因子水平。

enter image description here

是否有一個更簡單的把一個長方形當箱線圖具有離散x軸的箱線圖下方的方式?

回答

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

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

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