[R] ggplot "scale_x_date" : to plot quarterly scale?

Gabor Grothendieck ggrothendieck at gmail.com
Tue Oct 14 14:14:03 CEST 2014


On Tue, Oct 14, 2014 at 3:36 AM, jpm miao <miaojpm at gmail.com> wrote:
> Hi,
>
>   I am plotting time series by  ggplot2, but I believe that my question
> applies to other plotting tool as well.
>
>   I want to make my x-axis the quarterly scale, e.g:
> 2000Q1 2000Q2.....
>
>    However, scale_x_date and date_format("%m/%d") support all time formats
> BUT QUARTERs........
>
> library(scales) # to access breaks/formatting functions
> dt + scale_x_date()
> dt + scale_x_date(labels = date_format("%m/%d"))
>

1. zoo has a "yearqtr" class and its ggplot2 interface includes
scale_x_yearqtr() so:

library(zoo)
library(ggplot2)
library(scales)

# test data
DF <- data.frame(date = seq(as.Date("2014-01-01"), length = 4, by = "3
months"),
                             y = c(1, 4, 2, 3))

# convert date to yearmon class
DF2 <- transform(DF, date = as.yearqtr(date))

ggplot(DF2, aes(date, y)) + geom_line() + scale_x_yearqtr(format = "%YQ%q")

2. zoo also has a zoo method for ggplot2's autoplot generic so we
could just convert DF to zoo and write:

z <- zoo(DF$y, as.yearqtr(DF$date))
autoplot(z) + scale_x_yearqtr(format = "%YQ%q")

In both cases if the format argument is omitted one gets a default of
format = "%Y-%q".




-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list