2011-10-21 106 views
5

如果我有一些數據並做了方差分析和事後測試,我該如何製作一個自動添加事後分類的盒子圖,而不必編輯R之外的數字?R在anova boxplot上的Posthoc標籤

例如,這裏有一些數據開始:

install.packages("reshape", dependencies=T) 
library(reshape) 

x <- rnorm(30) 
y <- rnorm(30)+1 
z <- rnorm(30)+0.5 

data.1 <- data.frame(x, y, z) 
data.2 <- melt(data.1) 

下面是運行一個簡單的單因素方差分析,所有的計劃外的對比事後測試代碼:

linear.model <- lm(value~variable, data=data.2) 
anova(linear.model) 

# Analysis of Variance Table 
# Response: value 
#   Df Sum Sq Mean Sq F value Pr(>F) 
# variable 2 10.942 5.4710 5.8628 0.004087 ** 
# Residuals 87 81.185 0.9332  

TukeyHSD(aov(linear.model)) 

# Tukey multiple comparisons of means 
# 95% family-wise confidence level 
# Fit: aov(formula = linear.model) 
# $variable 
      # diff  lwr  upr  p adj 
# y-x 0.8344105 0.2396705 1.42915051 0.0034468 
# z-x 0.2593612 -0.3353788 0.85410126 0.5539050 
# z-y -0.5750493 -1.1697893 0.01969078 0.0602975 

在這一點,我想分組x,在組「a」,y在組「b」和z在組「a,b」。我可以製作一個boxplot,但是你如何用字母對它進行註釋?

boxplot(value~variable, data=data.2) 

回答

6

如果你不介意使用GGPLOT2包,這裏就是我會使人物:

首先,文本標籤欄添加到您的數據幀(data.2):

data.2$posthoc[data.2$variable == "x"] <- "a" 
data.2$posthoc[data.2$variable == "y"] <- "b" 
data.2$posthoc[data.2$variable == "z"] <- "a,b" 

安裝並加載GGPLOT2包:

install.packages("ggplot2", dependencies=T) 
library(ggplot2) 

要了解這個數字的代碼,我將在步驟構建它秒。首先剛繪製的手段爲三個組:

qplot(data=data.2, 
    x = variable, 
    y = value, 
    stat = "summary", 
    fun.y = "mean", 
    geom = c("point") 
    ) 

接下來,添加文本標籤:

qplot(data=data.2, 
    x = variable, 
    y = value, 
    stat = "summary", 
    fun.y = "mean", 
    label = posthoc, 
    vjust = -12, 
    geom = c("point", "text") 
    ) 

最後,添加箱線圖GEOM,並清理了一點:

qplot(data=data.2, 
    x = variable, 
    y = value, 
    stat = "summary", 
    fun.y = "mean", 
    label = posthoc, 
    vjust = -12, 
    ylim = c(-1, 3.5), 
    geom = c("point", "text"), 
    main="ggplot2 ANOVA boxplot" 
    ) + 
    geom_boxplot(aes(fill=posthoc)) + 
    theme_bw() 

R anova boxplot with labels

+0

工作!有沒有辦法在基本R圖形中做同樣的註釋? – user1006644

+1

是的,例如'boxplot'函數後面的文本(x = 1:3,y = 3,c(「a」,「b」,「b,c」)))。 – rcs

+0

謝謝James&RCS! – user1006644

2

這將是簡單

library(reshape) 

x <- rnorm(30) 
y <- rnorm(30)+1 
z <- rnorm(30)+0.5 

data.1 <- data.frame(x, y, z) 
data.2 <- melt(data.1) 
data.2$newgroup = factor(data.2$variable,labels=c("a","b","ab")) # only line added 
boxplot(value~newgroup, data=data.2) 
+0

謝謝Dieter,這很有幫助! – user1006644