3

我想查看因素组合的箱线图,并被告知为此使用 lattice。我试过了,它看起来像这样:

在此处输入图像描述 但现在我还想为每个组添加一个方差分析统计。可能统计数据应该在每个面板中显示 p 值(在例如“澳大利亚”下方的白色中)。如何在格中做到这一点?请注意,我根本不坚持格子......

示例代码:

set.seed(123)
n <- 300
country <- sample(c("Europe", "Africa", "Asia", "Australia"), n, replace = TRUE)
type <- sample(c("city", "river", "village"), n, replace = TRUE)
month <- sample(c("may", "june", "july"), n, replace = TRUE)
x <- rnorm(n)
df <- data.frame(x, country, type, month)

bwplot(x ~ type|country+month, data = df, panel=function(...) {
    panel.abline(h=0, col="green")
    panel.bwplot(...)
})

对其中一个组执行 ANOVA 并提取 p 值的代码如下:

model <- aov(x ~ type, data = df[df$country == 'Africa' & df$month == 'may',])
p_value <- summary(model)[[1]][["Pr(>F)"]][2]
4

1 回答 1

3

这是使用ggplot2. 首先,我们可以分别计算每个月/国家组合的 p 值(我使用data.table. 你可以使用任何你喜欢的方式)。然后,我们添加geom_text并指定pvalue为标签,并指定文本应该在每个方面内的 x 和 y 坐标。

require(data.table)
dt <- data.table(df)
pval <- dt[, list(pvalue = paste0("pval = ", sprintf("%.3f", 
        summary(aov(x ~ type))[[1]][["Pr(>F)"]][1]))), 
        by=list(country, month)]

ggplot(data = df, aes(x=type, y=x)) + geom_boxplot() + 
geom_text(data = pval, aes(label=pvalue, x="river", y=2.5)) + 
facet_grid(country ~ month) + theme_bw() + 
theme(panel.margin=grid::unit(0,"lines"), # thanks to @DieterMenne
strip.background = element_rect(fill = NA), 
panel.grid.major = element_line(colour=NA), 
panel.grid.minor = element_line(colour=NA))

在此处输入图像描述

于 2013-08-20T12:48:28.663 回答