Home > Software engineering >  Formatting x-axis in ggplot when axis tick labels are in Year-quarter
Formatting x-axis in ggplot when axis tick labels are in Year-quarter

Time:11-25

I have below ggplot

library(ggplot2)
library(zoo)
Dat = rbind(data.frame('name' = 'A', 'val' = sample(1:100, 10, replace = T), 'date' = as.yearqtr(seq(as.Date('2020-01-01'), by = '1 quarter', length.out = 10))),
            data.frame('name' = 'B', 'val' = sample(1:100, 10, replace = T), 'date' = as.yearqtr(seq(as.Date('2020-01-01'), by = '1 quarter', length.out = 10))),
            data.frame('name' = 'C', 'val' = sample(1:100, 10, replace = T), 'date' = as.yearqtr(seq(as.Date('2020-01-01'), by = '1 quarter', length.out = 10))))

ggplot(Dat, aes(x = date, y = val, fill = name)) 

However in the x-axis I want the tick labels should show something like 2020-Q1, 2020-Q2 etc instead of default labelling.

Is there any way to achieve this?

Any pointer will be very helpful

CodePudding user response:

You could modify zoo::scale_x_yearqtr format argument...

library(ggplot2)
library(zoo)
ggplot(Dat, aes(x = date, y = val, fill = name))  
  geom_point() 
  scale_x_yearqtr(format = "%Y-Q%q")

Created on 2021-11-24 by the reprex package (v2.0.1)

  • Related