[R] Plotting quarterly time series
ggrothendieck at gmail.com
Sun Jan 28 23:23:53 CET 2018
Using Achim's d this also works to generate z where FUN is a function used
to transform the index column and format is also passed to FUN.
z <- read.zoo(d, index = "time", FUN = as.yearqtr, format = "Q%q %Y")
On Sun, Jan 28, 2018 at 4:53 PM, Achim Zeileis <Achim.Zeileis at uibk.ac.at> wrote:
> On Sun, 28 Jan 2018, phil at philipsmith.ca wrote:
>> I have a data set with quarterly time series for several variables. The
>> time index is recorded in column 1 of the dataframe as a character vector
>> "Q1 1961", "Q2 1961","Q3 1961", "Q4 1961", "Q1 1962", etc. I want to produce
>> line plots with ggplot2, but it seems I need to convert the time index from
>> character to date class. Is that right? If so, how do I make the conversion?
> You can use the yearqtr class in the zoo package, converting with
> as.yearqtr(..., format = "Q%q %Y"). zoo also provides an autoplot() method
> for ggplot2-based time series visualizations. See ?autoplot.zoo for various
> ## example data similar to your description
> d <- data.frame(sin = sin(1:8), cos = cos(1:8))
> d$time <- c("Q1 1961", "Q2 1961", "Q3 1961", "Q4 1961", "Q1 1962",
> "Q2 1962", "Q3 1962", "Q4 1962")
> ## convert to zoo series
> z <- zoo(as.matrix(d[, 1:2]), as.yearqtr(d$time, "Q%q %Y"))
> ## ggplot2 display
> ## with nicer axis scaling
> autoplot(z) + scale_x_yearqtr()
> ## some variations
> autoplot(z, facets = Series ~ .) + scale_x_yearqtr() + geom_point()
> autoplot(z, facets = NULL) + scale_x_yearqtr() + geom_point()
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> PLEASE do read the posting guide
>> and provide commented, minimal, self-contained, reproducible code.
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
email: ggrothendieck at gmail.com
More information about the R-help