Geom_text with facet_wrap in ggplot2 if the specified group

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

boxplot example

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?

+5
source share
1 answer

When displaying aesthetics (i.e. aes(...,color = Subject) ) in a top-level call to ggplot() these mappings are passed to each level, which means that each layer expects data to have variables with these names.

You either need to specify the data and the mapping in each layer separately, or explicitly turn them off:

 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,color = NULL,group= NULL)) 

There is also an argument to inherit.aes , which you can set to FALSE at any level that you do not want to pull in other mappings, for example

 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),inherit.aes = FALSE) 
+8
source

Source: https://habr.com/ru/post/1239510/


All Articles