# Plotting quarterly time series

4 messages
Open this post in threaded view
|

## Plotting quarterly time series

 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? ______________________________________________ [hidden email] mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.
Open this post in threaded view
|

## Re: Plotting quarterly time series

 On Sun, 28 Jan 2018, [hidden email] 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 examples. ## 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 library("zoo") z <- zoo(as.matrix(d[, 1:2]), as.yearqtr(d\$time, "Q%q %Y")) ## ggplot2 display library("ggplot2") autoplot(z) ## 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() > ______________________________________________ > [hidden email] mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ [hidden email] mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.