我想在一組箱形圖上放置一個底層,以指示從單獨的源和單獨的數據框中繪製的一些數據的範圍。製作覆蓋圖很簡單;使襯墊很困難。當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))
這工作得很好 - 除了我(其實是:我共同作者)想要在之下具有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軸隆重推出的原因,我不明白額外的因子水平。
是否有一個更簡單的把一個長方形當箱線圖具有離散x軸的箱線圖下方的方式?