简体   繁体   中英

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:

用代码获得的图像

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:

我想要达到的目标

Thanks.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM