簡體   English   中英

R中anova boxplot上的Posthoc標簽

[英]Posthoc labels on anova boxplot in R

如果我有一些數據並進行ANOVA和事后測試,我如何制作一個自動添加事后分類的箱線圖,而不是編輯R外的數字?

例如,以下是一些入門數據:

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)

這是運行簡單的單向ANOVA和所有計划外比較事后測試的代碼:

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

此時,我想對組“a”中的x,組“b”中的y和組“a,b”中的z進行分類。 我可以制作一個箱形圖,但你怎么用字母注釋呢?

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

如果你不介意使用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")
    )

最后,添加boxplot 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標簽

這會更簡單

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM