MYaseen208 MYaseen208 - 1 month ago 27
R Question

Interaction Plot in ggplot2

I'm trying to make interaction plot with

ggplot2
. My code is below:

library(ggplot2)
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")
p <- p + stat_summary(fun.y = mean, geom = "line", aes(group = 1))
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)


How can I plot dose-supp level combination means rather than only dose level means which I'm getting here? Thanks in advance for your help.

enter image description here

Answer

You can precalculate the values in their own data frame:

toothInt <- ddply(ToothGrowth,.(dose,supp),summarise, val = mean(len))

ggplot(ToothGrowth, aes(x = factor(dose), y = len, colour = supp)) + 
    geom_boxplot() + 
    geom_point(data = toothInt, aes(y = val)) +
    geom_line(data = toothInt, aes(y = val, group = supp)) + 
    theme_bw()

enter image description here

Note that using ggplot rather than qplot makes the graph construction a lot clearer for more complex plots like these (IMHO).

Comments