Is there a way to find the names of the facets in a ggplot?

Viewed 62

I would like to add some curves to a ggplot with facets but I can not figure out how to correctly identify a particular panel with a particular name used for faceting. For instance:

a <- data.frame(Surg=c("Surg1", "Surg2", "Surg3","Surg1", "Surg2", "Surg3"), 
           Times=c(23,45,12,45,7,12))
plota <- ggplot(a) +
  geom_histogram(aes(Times)) +
  facet_wrap(~Surg)

I can then use ggplot_build(plota) to get a lot of information but I can't seem to find where the name of a particular panel is found. Any help would be greatly appreciated.

1 Answers

We could extract the data.frame in layout

p1 <- ggplot_build(plota)
p1$layout$layout
  PANEL ROW COL  Surg SCALE_X SCALE_Y
1     1   1   1 Surg1       1       1
2     2   1   2 Surg2       1       1
3     3   1   3 Surg3       1       1

The 'layout' is a data.frame with the PANEL and the names in 'Surg'. We just need to extract the 'Surg' column

p1$layout$layout$Surg
[1] "Surg1" "Surg2" "Surg3"
Related