Home > Enterprise >  format dates as quarters in ggplot2 x axis
format dates as quarters in ggplot2 x axis

Time:10-07

I have the following chart generated using ggplot2. Is there a way in which I can format my dates on the x axis as quarters (for example 2022-Q1) instead of the current date format which I have?

data <- structure(list(Date = structure(c(19083, 19086, 19087, 19088, 
19089, 19090, 19093, 19094, 19095, 19096, 19101, 19102, 19103, 
19104, 19107, 19108, 19109, 19110, 19111, 19114, 19115, 19116, 
19117, 19118, 19121, 19122, 19123, 19124, 19125, 19128, 19129, 
19130, 19131, 19132, 19135, 19136, 19137, 19138, 19139, 19143, 
19144, 19145, 19146, 19149, 19150, 19151, 19152, 19153, 19156, 
19157, 19158, 19159, 19160, 19164, 19165, 19166, 19167, 19170, 
19171, 19172, 19173, 19174, 19178, 19179, 19180, 19181, 19184, 
19185, 19186, 19187, 19188, 19191, 19192, 19193, 19194, 19195, 
19198, 19199, 19200, 19201, 19202, 19205, 19206, 19207, 19208, 
19209, 19212, 19213, 19214, 19215, 19216, 19219, 19220, 19221, 
19222, 19223, 19226, 19227, 19228, 19229, 19230, 19233, 19234, 
19235, 19236, 19237, 19241, 19242, 19243, 19244, 19247), class = "Date"), 
    US = c(-0.099, -0.082, -0.102, -0.276, -0.265, -0.214, -0.254, 
    -0.321, -0.263, -0.195, -0.189, -0.077, -0.025, -0.278, -0.543, 
    -0.595, -0.638, -0.587, -0.571, -0.754, -0.681, -0.597, -0.68, 
    -0.738, -0.942, -0.882, -0.657, -0.673, -0.468, -0.394, -0.323, 
    -0.357, -0.604, -0.533, -0.409, -0.529, -0.577, -0.496, -0.344, 
    -0.362, -0.326, -0.367, -0.365, -0.318, -0.43, -0.405, -0.515, 
    -0.658, -0.77, -1.033, -1.058, -1.217, -1.112, -1.096, -1.114, 
    -1.158, -1.013, -0.915, -0.863, -1.099, -1.192, -1.236, -1.395, 
    -1.144, -1.09, -1.167, -1.325, -1.378, -1.343, -1.492, -1.591, 
    -1.56, -1.254, -1.505, -1.327, -1.505, -1.542, -1.528, -1.526, 
    -1.591, -1.416, -1.513, -1.577, -1.389, -1.429, -1.486, -1.547, 
    -1.649, -1.61, -1.585, -1.475, -1.393, -1.307, -1.376, -1.571, 
    -1.744, -2.067, -2.294, -2.401, -2.423, -2.449, -2.69, -2.633, 
    -2.654, -2.812, -2.909, -3.037, -2.912, -2.456, -2.523, -2.51
    )), row.names = c(NA, -111L), class = c("tbl_df", "tbl", 
"data.frame"))

library(tidyverse)

ggplot(data, aes(Date, US))  
  geom_line(size=2)  
  scale_x_date(breaks = '3 months')

enter image description here

CodePudding user response:

You could try making use of the zoo package:

ggplot(data, aes(Date, US))  
  geom_line(size=2)  
  scale_x_date(breaks = "3 months", 
               labels = function(x) zoo::format.yearqtr(x, "%Y-Q%q"))
  • Related