Home > front end >  Independent y-axis per nested facet in ggplot
Independent y-axis per nested facet in ggplot

Time:08-20

Is it possible to have a second "free" y-axis specifically for the nester "Short leaves"? I do not want to have an independent y-axis for all 3, just 2 for the respective nesters. How can I do that?

library(tidyverse)
library(ggh4x)

df <- as_tibble(iris) %>%
  select(3, 5) %>%
  mutate(Nester = if_else(Species == "setosa", "Short Leaves", "Long Leaves"),
         Nester = factor(Nester))

df %>%
  pivot_longer(!c(Species, Nester), names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Measure, Value))  
  geom_boxplot()  
  facet_nested(~ Nester   Species)

EDIT: So far, I only found those two options that do free y-axis for all 3:

facet_nested(~ Nester   Species, scales = "free_y", independent = "y")

and

facet_nested_wrap(~ Nester   Species, scales = "free_y", nrow = 1)

which do not give the desired result.

CodePudding user response:

There isn't really a good amount of control at the facet levels about which panel uses which y-scale. However, facetted_pos_scales() gives you exactly that control.

Let's suppose we have this plot from your example.

library(tidyverse)
library(ggh4x)

df <- as_tibble(iris) %>%
  select(3, 5) %>%
  mutate(Nester = if_else(Species == "setosa", "Short Leaves", "Long Leaves"),
         Nester = factor(Nester))

p <- df %>%
  pivot_longer(!c(Species, Nester), names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Measure, Value))  
  geom_boxplot()  
  facet_nested(~ Nester   Species, scales = "free_y", independent = "y")

We can 'fix' a scale by giving it a constant limit, which we'd have to pre-calculate. You can then set that scale to some panels.

ylim <- range(df$Petal.Length[df$Nester == "Long Leaves"])

p   facetted_pos_scales(
  y = list(Nester == "Long Leaves" ~ scale_y_continuous(limits = ylim))
)

If you also wish to omit the axis in between the panels with fixed scales, you'd need to set the scales separately for each panel. In the middle panel, you'd have to set guide = "none" to hide the axis.

p   facetted_pos_scales(
  y = list(
    Species == "versicolor" ~ scale_y_continuous(limits = ylim),
    Species == "virginica"  ~ scale_y_continuous(limits = ylim, guide = "none")
  )
)

Created on 2022-08-19 by the reprex package (v2.0.0)

  • Related