R ggplot2 - setting breaks when also using facets

Viewed 30

I want to have some more flexibility for setting the breaks on a ggplot that has facets.

library(data.table)
library(tidyverse)
dt <- data.table(x = rnorm(1000),
                 group = sample(c(1,2), size=1000, replace = TRUE))

The problem is I want to create the breaks based off all of the data for a particular facet, but the documentation for breaks says:

A function that takes the limits as input and returns breaks as output (e.g., a function returned by scales::extended_breaks()). Also accepts rlang lambda function notation.

Note that you just get the limits of the data for that facet. Say I want to use the output of summary to create my breaks. E.g.:

breaks_f <- function(x){ 
  print(x) # included this to confirm I only get limits
  as.numeric(ceiling(summary(x)))
}

dt %>% 
  ggplot(aes(x=x)) +
  geom_density(adjust=.8, color = NA, alpha = .8, fill = 'blue')+
  scale_x_continuous(breaks = breaks_f) +
  facet_wrap(vars(group), scales = 'free')

You'll see if you run this, you'll get breaks that based off taking summary(c(min, max)) for each facet, not all of the data for that facet.

So is there a way to access all of the data within each facet?

Thanks!

1 Answers

One option would be ggh4x::facetted_pos_scales which allows to

... vary labels, breaks, limits, transformations and even axis guides for each panel individually.

Hence, using ggh4x::facetted_pos_scales you could apply your function and set the breaks individually for each panel:

library(data.table)
library(tidyverse)
library(ggplot2)
library(ggh4x)

set.seed(123)
dt <- data.table(
  x = rnorm(1000),
  group = sample(c(1, 2), size = 1000, replace = TRUE)
)

breaks_f <- function(x) {
  print(x) # included this to confirm I only get limits
  as.numeric(ceiling(summary(x)))
}

dt %>%
  ggplot(aes(x = x)) +
  geom_density(adjust = .8, color = NA, alpha = .8, fill = "blue") +
  facet_wrap(vars(group), scales = "free") +
  facetted_pos_scales(x = list(
    scale_x_continuous(breaks = breaks_f),
    scale_x_continuous(breaks = breaks_f)
  ))

#> [1] -2.937358  3.535249
#> [1] -2.937358  3.535249
#> [1] -3.084506  2.959591
#> [1] -3.084506  2.959591
Related