Skip to content

Customizing date labels in facet_zoom #346

@spencer-tassone

Description

@spencer-tassone

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions