如何在 ggplot 箱线图中的小平面包裹上获得双 y 轴(双胞胎)?

问题描述 投票:0回答:1

我有一个带有几个箱线图的 ggplot 图,我希望每组中的最后一个箱线图(在我的示例中是所有箱线图 c)显示在右侧的不同 y 轴上(最好用颜色标记)箱线图)。箱线图 c 显示了不同的测量值,其数量级可能会有很大差异,并且以不同的单位进行测量,因此它们与 a 和 b 共享轴是没有意义的。 (在我的示例中,我使用函数 o 和 f 更改了箱线图的定义。)

我的工作示例:

library(ggplot2)

a1 <- rnorm(n=100, mean=5, sd=20)
a2 <- rnorm(n=100, mean=6, sd=20)
a3 <- rnorm(n=100, mean=8, sd=20)

b <- rnorm(n=100, mean=11, sd=10)

c1 <- rnorm(n=100, mean=500, sd=80)
c2 <- rnorm(n=100, mean=600, sd=80)
c3 <- rnorm(n=100, mean=800, sd=80)

letters <- c(rep("a", 300), rep("b", 300), rep("c", 300))
type <- rep(c(rep(1,100), rep(2,100), rep(3,100)),3)

dat <- data.frame(y=c(a1,a2,a3,b,b,b,c1,c2,c3), letters, type)


f <- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}
o <- function(x) {
  subset(x, x < quantile(x, 0.05) | quantile(x, 0.95) < x)
}
ggplot(dat, aes(x=letters, y=y, fill=type, group=letters)) + 
  stat_summary(fun.data = f, geom="boxplot", fill="white") +
  stat_summary(fun = o, geom="point") + facet_wrap(~type, nrow=1) +  
  guides(fill="none")

结果

我想要什么

当然,一旦轴不再共享,轴范围就会改变,我想要这样,但这太难画了。 (如果两个轴都从零开始就可以了,但最大值应该随数据而变化。)

提供一些背景信息:a、b 和 c 代表判断每种类型有效性的标准。我希望以这种方式表示图,这样我就可以轻松地分别判断每个选项(类型 1,2,3)(因此这些字母彼此相邻),然后还能够比较不同类型并做出权衡。理想情况下,您将在最后根据情节选择一种类型。

我只在 ggplot 中找到了一种孪生 y 的方法,即现有 y 轴的转换。这也许可行,但我不知道如何让它只适用于 w 箱线图。

r ggplot2 plot boxplot
1个回答
0
投票

不确定您想要如何在辅助比例上设置变换,但为了演示,我将其保留为 1。

ggplot(dat, aes(x=letters, y=y, fill=type, group=letters)) + 
  stat_summary(aes(color=letters), fun.data=f, geom="boxplot", fill="white") +
  scale_color_manual(values=c("c" = "#ff00ff"), na.value="#000000")+
  stat_summary(fun=o, geom="point") + 
  scale_y_continuous(sec.axis=sec_axis(transform=~.*1)) +
  facet_wrap(~type, nrow=1, axes="all", scales="free") + 
  guides(fill="none", color="none")+
  theme(axis.text.y.right=element_text(color="#ff00ff"))
© www.soinside.com 2019 - 2024. All rights reserved.