Home > Mobile >  R ggplot: major gridlines / quarter label misplaced
R ggplot: major gridlines / quarter label misplaced

Time:01-24

I am trying to plot a geom_smooth of a time series variable. It is daily data starting on January 1st 2019. I want to have the major gridlines and horizontal axis display the quarter. But it ends up putting the 2019-Q1 label and the END of the quarter, and I would like to have it at the beginning of that quarter.

Here is my code:

ggplot(data = stackoverflow, aes(x=Date , y=Value, col=MyName))  
  geom_smooth(method = "loess", span = 0.5, se=FALSE, size=2)  
  scale_x_date(date_breaks = "3 months", minor_breaks = "1 month", labels = function(x) zoo::format.yearqtr(x, "%Y-Q%q"))  
  coord_cartesian(ylim = c(-0.03,0.03))  
  geom_point(aes(Date, Value))  
  xlab("Quarter")  
  theme(panel.grid.major = element_line(colour="white", size=1.5))

(I have added geom_point to show the individual data points, but they will not be used in my final presentation of the chart.)

Here is the result: enter image description here

As you can see, the data seems to start before 2019-Q1, but I really have data from Jan 1st 2019 onwards. And the data seems to end before 2022-Q1, but I really have data that includes December 2021, and even a few points in January 2022.

Is there any way to have the major gridlines and the tick label show up at the BEGINNING of the quarter? I tried adding 30 days to the date, but then it shows 2019-Q2 at the first major gridline, and I do really like the 2019-Q1 as first tick label.

CodePudding user response:

If the date_breaks parameter isn't giving you what you want, use the breaks parameter instead. Just pass it a vector of the dates that you want to use for the major breaks. It's easy to create one using seq

my_breaks <- seq(from = as.Date("2019-01-01"), to = as.Date("2022-01-01"), by = "3 months")

ggplot(data = stackoverflow, aes(x = Date , y = Value, col = MyName))  
  geom_smooth(formula = y ~ x, method = "loess", span = 0.5, se = FALSE, size = 2)  
  geom_point()  
  scale_x_date(breaks = my_breaks, minor_breaks = "1 month", 
               labels = function(x) zoo::format.yearqtr(x, "%Y-Q%q"))  
  scale_color_manual(values = "#06aee7")  
  xlab("Quarter")  
  coord_cartesian(ylim = c(-0.03, 0.03))  
  theme(panel.grid.major = element_line(colour = "white", size = 1.5))

enter image description here


Data used

set.seed(1)
stackoverflow <- data.frame(Date = seq(as.Date("2019-01-01"), 
                                       as.Date("2022-01-10"), 
                                       by = "1 day"),
                            Value = rnorm(1106)/40,
                            MyName = "series name")
  •  Tags:  
  • Related