I would like to have two x axes. One of them (primary preferably) having year quarter and the second one having the months. I'm trying to do this, since my date observations are not uniform/sequential. i.e I can have only Jan in Q1, but the whole 3 months in Q2.
My attempt was to use scale_x_date
having the date in the standard date format (as.Date()
) and using date_labels
and breaks
.
For the secondary axis, I've used dup_axis
and passed zoo::as.yearqtr
.
library("zoo")
library("ggplot2")
set.seed(44)
## Creating a reproducible data-frame ##
df <- data.frame("id" = sample(1:100, 3, replace=TRUE),
"date" = c("2020-01-01","2020-02-01","2020-03-01",
"2020-04-01",
"2020-07-01","2020-09-01",
"2020-10-01","2020-11-01","2020-12-01")
)
## Plotting ##
df %>%
{
ggplot(data = ., aes(x = as.Date(date), y = id, group = 1)) +
geom_line() +
geom_point() +
scale_x_date(date_labels = "%b", breaks = "1 month",
sec.axis = dup_axis(name = "month", breaks = scales::date_breaks("3 month"), labels = as.yearqtr)
)
}
Here is a plot image of my attempt:
The downsides I'm facing here:
- The quarter is being plotted for the last 3rd month (i.e it will match March), I'd like for it to match January instead.
Extras - Other low severity issues are:
All dates are plotted, I guess it's because I'm using
scale_x_date
and we should usescale_x_discrete
.. It would be helpful if we wrote labels for only points that exist, otherwise I'm okay for the viewer to match/interpret the points with his eyes.This is the lowest severity, but I would like to pass arguments to function
as.yearqtr
so I can format quarter. i.e This will yieldas.yearqtr(Sys.Date()) %>% format("%y Q%q")
"20 Q2" instead of "2020 Q2"