Home > Enterprise >  Fixing the number of ticks in x axis when x axis is date
Fixing the number of ticks in x axis when x axis is date

Time:10-16

I have below ggolot

library(ggplot2)
library(quantmod)
dat = data.frame(val = 1:20, qtr = as.yearqtr(seq(as.Date('2000-01-01'), length.out = 20, by = '3 months')))

ggplot(data = dat)  
  geom_line(aes(x = qtr, y = val))  
  scale_x_yearqtr(n = 7)

With this I am not able to fix the number of ticks as 7, it is reporting only 5. Is there any way to hard-fix number of ticks at 7?

Thanks for your help.

CodePudding user response:

The function help for scale_x_yearqtr suggests n provides "Approximate number of axis ticks." So one option may be to create a specific set of breaks as required...

library(ggplot2)
library(quantmod)

df_breaks <-  data.frame(dates = as.yearqtr(seq(as.Date('2000-01-01'), length.out = 7, by = '9 months')))


ggplot(data = dat)  
  geom_line(aes(x = qtr, y = val))  
  scale_x_yearqtr(breaks = df_breaks$dates)

Created on 2022-10-15 with reprex v2.0.2

  • Related