ggforce icon indicating copy to clipboard operation
ggforce copied to clipboard

Customizing date labels in facet_zoom

Open spencer-tassone opened this issue 5 months ago • 0 comments

I have a daily timeseries for one year and want to make a zoomed out plot that shows the whole timeseries and a zoomed in plot on a few specific dates. For the zoomed out plot, I want the x-axis to show the month and year stacked on top of one another, which can be achieved using scale_x_date(date_labels = '%b\n%Y'). However, in the zoomed in plot, I want to show month and day. I am trying to do this using ggforce::facet_zoom() but it seems to inherit the date_labels from scale_x_date. How can I customize the date labels when using facet_zoom?

The ideal output would have the zoomed out plot with date_labels = '%b\n%Y' and the zoomed in plot would have date_labels = '%b %d'

library(tidyverse)
library(ggforce)

# Example data
dat <- data.frame(
  date = seq(as.Date('2024-01-01'),
             as.Date('2024-12-31'),
             '1 day'),
  value = rnorm(366, 10, 3)
)

# Plot 1: without setting date_labels, the default is to show the month and year while the zoomed plot shows month and day
dat |> 
  ggplot(aes(x = date, y = value)) +
  geom_point() +
  labs(x = NULL,
       y = 'Value') +
  theme_bw(base_size = 16) +
  facet_zoom(xlim = c(as.Date("2024-06-01"), as.Date("2024-06-20")))

# Plot 2: when I set the date_labels for the zoomed out plot, the day no longer shows in the zoomed in plot
dat |> 
  ggplot(aes(x = date, y = value)) +
  geom_point() +
  scale_x_date(breaks = seq(as.Date('2024-01-01'),
                            as.Date('2024-12-31'),
                            '1 month'),
               limits = c(as.Date('2024-01-01'),
                          as.Date('2024-12-31')),
               date_labels = '%b\n%Y') +
  labs(x = NULL,
       y = 'Value') +
  theme_bw(base_size = 16) +
  facet_zoom(xlim = c(as.Date("2024-06-01"), as.Date("2024-06-20")))

Created on 2025-08-13 with reprex v2.1.1

I have also asked this question on stack overflow.

spencer-tassone avatar Aug 13 '25 20:08 spencer-tassone