Home > Enterprise >  Annotating each facet of a grid
Annotating each facet of a grid

Time:07-08

I'm looking to add a text box to each facet of a ggplot facet_grid. I have a data frame similar to this:

test<- structure(list(group = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 
3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5), species = c("A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "C", 
"C", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C", 
"C", "C", "C"), value = c(10, 7, 4, 3, 1, 9, 3, 2, 2, 1, 6, 4, 
3, 1, 1, 4, 3, 3, 2, 1, 10, 9, 6, 3, 1, 7, 7, 4, 2, 1), season = c("spring", 
"spring", "spring", "spring", "spring", "spring", "spring", "spring", 
"spring", "spring", "spring", "spring", "spring", "spring", "spring", 
"fall", "fall", "fall", "fall", "fall", "fall", "fall", "fall", 
"fall", "fall", "fall", "fall", "fall", "fall", "fall")), row.names = c(NA, 
-30L), class = "data.frame")

It is plotted with the following:

ggplot(test, aes(x=group, y=value)) 
  geom_point(size=2, show.legend=F) 
  geom_line() 
  facet_grid(season ~ species, scales= "fixed") 
  xlab("") 
  ylab("") 
  scale_x_continuous(limits = c(1,5), breaks=seq(1,5,1)) 
  theme_light() 
  theme(strip.text = element_text(face = "bold", color = "black",
                                  hjust = .5, size = 10),
        strip.background = element_rect(color = "black"),
        panel.border = element_rect(color="black"), 
        panel.grid.minor.x= element_blank(),
        panel.grid.minor.y = element_blank())

And I have a data frame that contains the label for each panel:

labels<- structure(list(label = c("n=1", "n=2", "n=3", "n=4", "n=5", "n=6"
), species = c("A", "B", "C", "A", "B", "C"), season = c("spring", 
"spring", "spring", "fall", "fall", "fall"), x = c(4, 4, 4, 4, 
4, 4), y = c(8, 8, 8, 8, 8, 8)), row.names = c(NA, -6L), class = "data.frame")
# the X and Y columns are the coordinates of where I want the label to appear in each facet

I was able to get the desired output when I only use a facet_wrap, but when doing a grid I cant get the labels to correspond to both the correct row and column.

Any help/insight would be greatly appreciated.

CodePudding user response:

I might not be appreciating the difficulty here, but it seems to me that geom_text() would simply do the job adequately.

ggplot(test, aes(x=group, y=value)) 
  geom_point(size=2, show.legend=F) 
  geom_line() 
  geom_text(aes(x = x, y = y, label = label),
            data = labels)  
  facet_grid(season ~ species, scales= "fixed") 
  xlab("") 
  ylab("") 
  scale_x_continuous(limits = c(1,5), breaks=seq(1,5,1)) 
  theme_light() 
  theme(strip.text = element_text(face = "bold", color = "black",
                                  hjust = .5, size = 10),
        strip.background = element_rect(color = "black"),
        panel.border = element_rect(color="black"), 
        panel.grid.minor.x= element_blank(),
        panel.grid.minor.y = element_blank())

  • Related