Posthoc labels on anova boxplot in R

假如想象 提交于 2019-11-30 09:58:11

If you don't mind using the ggplot2 package, here's how I would make the figure:

First, add a column to your data frame (data.2) with the text labels:

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"

Install and load the ggplot2 package:

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

To understand the code for the figure, I'll build it in steps. First just plot the means for each of the three groups:

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

Next, add the text labels:

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

Finally, add the boxplot geom and clean it up a little:

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

This would be simpler

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!