Search code examples
rggplot2facet

How to change the position of one of the facet_nested labels?


I have a plot for which I would like to place one facet label in the top and the other one on the left side of the plot. However, I don't know if that is possible or if I should do it in an other way. Below I show a fake example to play with:

library(ggplot2)
library(ggsci)
library(ggthemes)
library(ggh4x)

df <- data.frame(x=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28),
                 y=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28))
df$Method <- "Pearson"
df$ID <- "A"

Plot <-  ggplot(df, aes(x=x, y=y)) + 
  geom_point(size=.8) + 
  theme_hc() +
  theme(strip.background = element_rect(colour = "black", fill = "white", 
                                        size = 1.5, linetype = "solid"),
        axis.title.x =element_blank(),
        axis.title.y =element_blank(),
        axis.text.x = element_text(angle = 0, hjust = 0.5,size = 10.5, face="bold"),
        axis.text.y = element_text(angle = 0, hjust = 0.5,size = 10.5),
        strip.text.x = element_text(size = 9),
        strip.text.y = element_text(size = 13),
        axis.line = element_line(),
        panel.grid.major= element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=9),
        legend.title = element_text(size=10,face="bold"),
        legend.key=element_blank(),
        legend.justification = c(0.5,0),
        legend.position = "right",
        panel.border = element_blank(),
        strip.placement = "outside",
        plot.title = element_text(size = 16, hjust = 0.5),
        strip.switch.pad.grid = unit('0.1', "cm")) + 
  labs(x= '\nTime delay (modifiable device)',y=expression(R^{2})) +
  guides(color=guide_legend(override.aes=list(fill=NA))) +
  scale_y_continuous(limits = c(0., 30), breaks = c(5, 15,25)) +
  facet_wrap(Method~ID) +
  scale_color_jco() 

Plot

enter image description here

I would like to place the A label in the left part of the plot? Does anyone know how to do it?

Thanks


Solution

  • I'm sorry for stripping away most of the plotting code, but the following captures the essence and requires less additional packages.

    facet_wrap() only puts strips on one side of the plot. If you need two sides with strips, you can use facet_grid(). To place the strip on the left, you can use the switch = 'y' argument.

    library(ggplot2)
    
    df <- data.frame(x=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28),
                     y=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28))
    df$Method <- "Pearson"
    df$ID <- "A"
    
    ggplot(df, aes(x=x, y=y)) + 
      geom_point(size=.8) + 
      facet_grid(Method~ID, switch = 'y')