Home > Back-end >  In ggplot2, is there a way to reverse the Y-axis on just one of several facets?
In ggplot2, is there a way to reverse the Y-axis on just one of several facets?

Time:10-29

In ggplot2, is there a way to reverse the Y-axis on just one of several facets?

I want to avoid generating multiple individual plots and combining via, e.g., the patchwork package.

Using the supplied data, I would like the axis of group C in the plot below to be reversed.

library(tidyverse)

# Data
set.seed(1)
df <- tibble(
  A1 = rnorm(50, 1, 1),
  A2 = rnorm(50, 2, 1),
  A3 = rnorm(50, 3, 1),
  B1 = rnorm(50, 10, 10),
  B2 = rnorm(50, 20, 10),
  B3 = rnorm(50, 30, 10),
  C1 = rnorm(50, 200, 50),
  C2 = rnorm(50, 150, 50),
  C3 = rnorm(50, 100, 50)) %>% 
  pivot_longer(cols = everything()) %>% 
  extract(name, into = c("Activity", "Group"), regex = "([A|B|C])([0-9])") 

head(df)
#> # A tibble: 6 x 3
#>   Activity Group  value
#>   <chr>    <chr>  <dbl>
#> 1 A        1      0.374
#> 2 A        2      2.40 
#> 3 A        3      2.38 
#> 4 B        1     14.5  
#> 5 B        2     24.1  
#> 6 B        3     31.4

# PLot
df %>% 
  ggplot(aes(x = Group, y = value, color = Group, fill = Group)) 
  geom_jitter(width = 0.15) 
  geom_boxplot(alpha = 0.1, color = "black", outlier.shape = NA) 
  facet_wrap(~Activity, scales = "free") 
  theme_bw()

Created on 2021-10-28 by the reprex package (v2.0.1)

CodePudding user response:

As pointed out by stefan, yes you can do this with ggh4x. Example below:

library(tidyverse)  
  
set.seed(1)
df <- tibble(
  A1 = rnorm(50, 1, 1),
  A2 = rnorm(50, 2, 1),
  A3 = rnorm(50, 3, 1),
  B1 = rnorm(50, 10, 10),
  B2 = rnorm(50, 20, 10),
  B3 = rnorm(50, 30, 10),
  C1 = rnorm(50, 200, 50),
  C2 = rnorm(50, 150, 50),
  C3 = rnorm(50, 100, 50)) %>% 
  pivot_longer(cols = everything()) %>% 
  extract(name, into = c("Activity", "Group"), regex = "([A|B|C])([0-9])") 

# PLot
df %>% 
  ggplot(aes(x = Group, y = value, color = Group, fill = Group)) 
  geom_jitter(width = 0.15) 
  geom_boxplot(alpha = 0.1, color = "black", outlier.shape = NA) 
  facet_wrap(~Activity, scales = "free") 
  ggh4x::facetted_pos_scales(y = list(
    Activity == "C" ~ scale_y_reverse()
  ))  
  theme_bw()
#> Warning in grid.Call.graphics(C_polygon, x$x, x$y, index): semi-transparency is
#> not supported on this device: reported only once per page

Created on 2021-10-28 by the reprex package (v0.3.0)

(Disclaimer: I'm the author of ggh4x)

  • Related