2013-08-20 87 views
3

我希望看到这些因素组合的盒形图和I was told to use lattice。我试过了,它看起来像这样:如何绘制每个组的boxplot中的附加统计数据?

enter image description here 但是现在我想为每个组添加一个ANOVA统计数据。可能统计数据应该在每个面板中显示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(...) 
}) 

进行方差分析的群体之一,并extract p-value的代码是这样的:

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

回答

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)) 

enter image description here

+0

感谢阿伦!但请如何删除可怕的ggplot网格? :) BTW非常优雅的使用数据表!不知道他们太优雅了! – TMS

+0

:)刚刚用'theme_bw()'编辑。这看起来好吗? – Arun

+0

更好:)如果我想完全摆脱它(所以它看起来不像它是从ggplot :-)) – TMS

相关问题