Interaction Plot in ggplot2

前端 未结 4 1615
情深已故
情深已故 2020-12-28 16:16

I\'m trying to make interaction plot with ggplot2. My code is below:

library(ggplot2)
p <- qplot(as.factor(dose), len, data=ToothGrowth, geom         


        
4条回答
  •  粉色の甜心
    2020-12-28 16:48

    You can compute your summaries by the appropriate groups (supp):

    p <- qplot(as.factor(dose), len, data=ToothGrowth, geom = "boxplot", color = supp) + theme_bw()
    p <- p + labs(x="Dose", y="Response")
    p <- p + stat_summary(fun.y = mean, geom = "point", color = "blue", aes(group=supp))
    p <- p + stat_summary(fun.y = mean, geom = "line", aes(group = supp))
    p <- p  + opts(axis.title.x = theme_text(size = 12, hjust = 0.54, vjust = 0))
    p <- p  + opts(axis.title.y = theme_text(size = 12, angle = 90,  vjust = 0.25))
    print(p)
    

    Or converting to ggplot syntax (and combining into one expression)

    ggplot(ToothGrowth, aes(as.factor(dose), len, colour=supp)) +
      geom_boxplot() +
      stat_summary(aes(group=supp), fun.y = mean, geom="point", colour="blue") +
      stat_summary(aes(group=supp), fun.y = mean, geom="line") +
      scale_x_discrete("Dose") +
      scale_y_continuous("Response") +
      theme_bw() +
      opts(axis.title.x = theme_text(size = 12, hjust = 0.54, vjust = 0),
        axis.title.y = theme_text(size = 12, angle = 90,  vjust = 0.25))
    

    EDIT:

    To make this work with 0.9.3, it effectively becomes Joran's answer.

    library("plyr")
    summ <- ddply(ToothGrowth, .(supp, dose), summarise, len = mean(len))
    
    ggplot(ToothGrowth, aes(as.factor(dose), len, colour=supp)) +
      geom_boxplot() +
      geom_point(data = summ, aes(group=supp), colour="blue", 
                 position = position_dodge(width=0.75)) +
      geom_line(data = summ, aes(group=supp), 
                position = position_dodge(width=0.75)) +
      scale_x_discrete("Dose") +
      scale_y_continuous("Response") +
      theme_bw() +
      theme(axis.title.x = element_text(size = 12, hjust = 0.54, vjust = 0),
            axis.title.y = element_text(size = 12, angle = 90,  vjust = 0.25))
    

    enter image description here

提交回复
热议问题