Home > OS >  Is there an R function to get the max y-axis when doing ggplot facet?
Is there an R function to get the max y-axis when doing ggplot facet?

Time:12-11

I have a facet graph where it's free = scales, so each plot has a different y-axis. I want to know if there is a function that can return the max y-axis so that the text always appears on the top of each plot, like this:

geom_text(data,aes(x=25,y=max_y,label="test text"))

I haven't been able to find any resources similar to this issue and was struggling to see if I could extract the layout information with ggplot_build or g_table. If I missed a resource, please let me know! Thank you in advance.

CodePudding user response:

ggplot(mtcars, aes(wt,mpg))  
  geom_point()  
  annotate("text", x = -Inf, y = Inf, label= "Test", 
           hjust = -0.2, vjust = 1.2)  
  facet_wrap(~gear, scales = "free")

enter image description here

Or with facet-varying data:

ggplot(mtcars, aes(wt,mpg))  
  geom_point()  
  geom_text(data = data.frame(wt = -Inf, mpg = Inf, gear = 3:5, 
                              label = c("Test", "More", "And more")),
            aes(label = label),
            hjust = -0.2, vjust = 1.2)  
  facet_wrap(~gear, scales = "free")

enter image description here

  • Related