Search code examples
rggplot2facet-grid

R: Align facet_grid() to the top of the grid


I am struggling trying to format the facet_grid of a plot in R. This is a reproducible example of my code with data avaliable from the datasets package in R (ToothGrowth).

library(ggplot2)

df <- ToothGrowth

bp <- ggplot(df, aes(x=dose, y=len, group=dose)) +
             geom_boxplot(aes(fill=dose)) +   
             facet_grid(supp ~ .) + 
             theme_minimal(base_size = 16) +   
             theme(legend.position = "none",
                   axis.title.x = element_blank(),
                   axis.title.y = element_blank(),
                   axis.ticks = element_blank(),
                   panel.grid.major.x = element_line(size = 0.25,
                                                     colour = "grey80"),
                   strip.text = element_text(size = 22, face = "bold"))

bp

With the code I obtain this first image:

Image obtained with the code

I want to align the labels of the facet_grid to the top of the grid legend, as you can see in the second image:

What I want to achieve

Thanks.


Solution

  • Add the following to your plot code:

    theme(strip.text.y=element_text(hjust=0))
    

    If you want to rotate the labels, you can do:

    theme(strip.text.y=element_text(vjust=1, angle=0))
    

    (Yes, the vjust vs. hjust thing is confusing)

    p1 = bp + theme(strip.text.y=element_text(hjust=0))
    p2 = bp + theme(strip.text.y=element_text(vjust=1, angle=0))
    

    enter image description here