When using ggplot2 to create faceted graphs, I have problems getting separate labels in each face, when I also specify the grouping option. Without specifying group = ... everything works fine, but I'm trying to make paired data graphs that underline before and after the changes.
Here is an example:
library(tidyr) library(ggplot2) set.seed(253) data <- data.frame(Subject = LETTERS[1:10], Day1.CompoundA = rnorm(10, 4, 2), Day2.CompoundA = rnorm(10, 7, 2), Day1.CompoundB = rnorm(10, 5, 2), Day2.CompoundB = rnorm(10, 5.5, 2)) # Compare concentration of compounds by day A <- t.test(data$Day1.CompoundA, data$Day2.CompoundA, paired = TRUE) B <- t.test(data$Day1.CompoundB, data$Day2.CompoundB, paired = TRUE) data.long <- gather(data, key = DayCompound, value = Concentration, -Subject) %>% separate(DayCompound, c("Day", "Compound")) # text to annotate graphs graphLabels <- data.frame(Compound = c("CompoundA", "CompoundB"), Pval = paste("p =", c(signif(A$p.value, 2), signif(B$p.value, 2))))
Ok, now that the data is configured, I can make boxplot just fine:
ggplot(data.long, aes(x = Day, y = Concentration)) + geom_boxplot() + facet_wrap(~ Compound) + geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval))

But if I want to show line graphs that emphasize the paired nature of the data, showing each object in a different color, the facet labels do not work.
ggplot(data.long, aes(x = Day, y = Concentration, color = Subject, group = Subject)) + geom_point() + geom_line() + facet_wrap(~ Compound) + geom_text(data = graphLabels, aes(x = 1.5, y = 10, label = Pval)) # Error in eval(expr, envir, enclos) : object 'Subject' not found
Any suggestions?