我正在使用包
ggh4x
以及以下集合和代码来创建一个箱线图,该箱线图在两个分类变量之间具有嵌套关系。
使用的数据
set1 <- structure(list(Tx = c("Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed",
"Not Exposed", "Not Exposed", "Exposed", "Exposed", "Exposed", "Exposed", "Exposed",
"Exposed", "Exposed", "Exposed", "Exposed", "Exposed", "Not Exposed", "Not Exposed",
"Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Not Exposed", "Exposed", "Exposed",
"Exposed", "Exposed", "Exposed", "Exposed", "Exposed", "Exposed",
"Exposed", "Exposed"), Species = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), levels = c("Species1", "Species2"), class = "factor"), Size = c(88.5,
83.3, 59.5, 78, 50.3, 57, 78.2, 59, 85, 59.5, 13.1, 50.1, 55,
60.1, 13.8, 27, 57.1, 53.1, 42, 16, 88.8, 26.2, 62, 108.5, 92.3,
74.4, 77.3, 96, 88.7, 77.8, 50.7, 61.9, 65.1, 63.5, 64, 88.6,
53.8, 82.1, 78.8, 75.6)), row.names = c(NA, -40L), class = c("tbl_df",
"tbl", "data.frame"))
嵌套箱线图
library(ggplot2)
library(ggh4x)
ggplot(set1, aes(x=interaction(Tx, Species), y=Size)) +
stat_boxplot(geom="errorbar", width = 0.15) +
geom_boxplot(show.legend=FALSE, outlier.shape = NA, aes(fill = interaction(Tx, Species))) +
geom_jitter(width = 0.1, shape=21, colour="black", fill="grey95", stroke=0.5, size=1) +
guides(x="axis_nested") +
theme_classic() +
theme(axis.title = element_text(face="bold"),
text = element_text(family = "serif", size = 12.5))
现在,嵌套关系就像我想要的那样显示在 x 轴上。但是,组的顺序是按字母顺序排列的,我想自己选择它(“未暴露”组位于“暴露”之前)。
我尝试使用
weave_factors()
而不是 interaction()
来完成此操作,但绘图无法正确显示嵌套关系。
您必须将
set1$Tx
转换为因子,然后将 "Not Exposed"
设置为第一级:
set1$Tx <- relevel(factor(set1$Tx), ref = "Not Exposed")