ah bon
ah bon

Reputation: 10011

ggplot2::scale_x_yearqtr gives wrong year in year-quarter format plot

Given a dataframe containing date column as follows:

enter image description here

I'm trying to plot date with format year-quartor by scale_x_yearqtr(format = "%YQ%q", breaks = df$date), but it gives the result like this:

enter image description here

In fact, it should be 2019Q1, 2019Q2, ..., 2020Q3, someone could help me figure out why it couldn't plot date correctly? Thanks.

Data:

x <- structure(list(date = structure(1:4, .Label = c("2020-03-01", 
"2020-06-01", "2020-09-01", "2020-12-01"), class = "factor"), 
    value = c(12L, 34L, 15L, 50L)), class = "data.frame", row.names = c(NA, 
-4L))

Code:

x$date <- as.Date(x$date, format = '%Y-%m-%d')

ggplot(x, aes(x = date, y = value, group = 1)) + 
  geom_line() +
  geom_point() +
  xlab('Date') +
  ylab('Value') +
  scale_x_yearqtr(format = '%YQ%q', breaks = df$date) 

Out:

enter image description here

Upvotes: 1

Views: 405

Answers (1)

ah bon
ah bon

Reputation: 10011

Problem solved by adding the following code before ggplot visualization chunk:

df$date <- as.yearqtr(df$date, format = '%Y-%m-%d')

Upvotes: 1

Related Questions