Search code examples
rggplot2facet-wrapfacet-grid

y-axis labels on opposite sides in `facet_wrap`


I would like to plot a facet_wrap of 2 groups, and have the y-axis labels on the left on the left plot, and the right on the right plot.

Here is the normal behavior. Both y-axis labels on the left.

library(tidyverse)

mtcars %>% mutate(let = rep(LETTERS[1:2], times = nrow(mtcars)/2),
                       make = rownames(mtcars))  %>% 
ggplot(aes(y = make, x = mpg)) + 
geom_point() +
facet_wrap(~ let, scales = "free")

Created on 2023-05-15 with reprex v2.0.2

I would like to have the B plot y-axis labels on the right side of the plot, but keep the A axis labels on the left side of the plot. Is this possible?


Solution

  • One option is to make two plots and use patchwork to combine them:

    library(dplyr)
    library(ggplot2)
    quux <- mtcars %>%
      mutate(
        let = rep(LETTERS[1:2], times = nrow(mtcars)/2),
        make = rownames(mtcars)
      )
    gg1 <- filter(quux, let == "A") %>%
      ggplot(aes(y = make, x = mpg)) +
      geom_point() +
      facet_wrap(~ let, scales = "free")
    gg2 <- filter(quux, let == "B") %>%
      ggplot(aes(y = make, x = mpg)) +
      geom_point() +
      facet_wrap(~ let, scales = "free") +
      scale_y_discrete(position = "right")
    
    library(patchwork)
    gg1 + gg2
    

    enter image description here