I'm wondering whether someone can help me in applying the facetscales
package to create different date ranges for each facet. I know something similar can be achieved using scales = "free_x"
in the call to ggplot
, but I am hoping to use this to also programmatically determine the number of days by which each facet's scale should be expanded.
I have seen a related question answered here (see Uwe's answer), but I cannot get the code to evaluate correctly with dates.
I have included a short example of my data below. From Uwe's answer to the question, the I expect a list of ggplot ggproto objects that can be included as a list in the plotting function, however, the code does not seem to evaluate the dates properly.
Any help much appreciated.
df <- structure(list(zone = c("zone1", "zone1", "zone1", "zone1", "zone1",
"zone1", "zone1", "zone1", "zone1", "zone1", "zone2", "zone2",
"zone2", "zone2", "zone2", "zone2", "zone2", "zone2", "zone2",
"zone2"), date = structure(c(16294, 16295, 16296, 16297, 16298,
16299, 16300, 16301, 16302, 16303, 16304, 16305, 16306, 16307,
16308, 16309, 16310, 16311, 16312, 16313), class = "Date"), Q = c(317,
299, 290, 276, 277, 238, 239, 266, 278, 278, 93, 102, 107, 124,
122, 110, 93, 89, 85, 92)), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -20L), groups = structure(list(
zone = c("zone1", "zone2"), .rows = list(1:10, 11:20)), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))
facet_params <- df %>%
group_by(zone) %>%
summarise(start_date=min(date, na.rm=TRUE), end_date=max(date, na.rm=TRUE)) %>%
mutate(duration = end_date-start_date,
extra_days = trunc(as.integer(duration)*.3),
breaks=c(2,4))
scales_y <- facet_params %>%
str_glue_data(
"`{zone}` = scale_x_date(limits = c({as.Date(start_date)}, {as.Date(end_date)}), ",
"breaks = seq({as.Date(start_date)}, {as.Date(end_date)}, {breaks}))") %>%
str_flatten(", ") %>%
str_c("list(", ., ")") %>%
parse(text = .) %>%
eval()