Time Series Plots Using ggplot2

Of course, the ggplot2 can also visualize time series. This section introduces the relevant ggplot2 syntax.

Basic ggplot of time series

  • Plot types: line plot with dates on x-axis
  • Demo data set: economics [ggplot2] time series data sets are used.

In this section we'll plot the variables psavert (personal savings rate) and uempmed (number of unemployed in thousands) by date (x-axis).

  • Load required packages and set the default theme:
library(ggplot2)
theme_set(theme_minimal())
# Demo dataset
head(economics)
## # A tibble: 6 x 6
##         date   pce    pop psavert uempmed unemploy
##                    
## 1 1967-07-01   507 198712    12.5     4.5     2944
## 2 1967-08-01   510 198911    12.5     4.7     2945
## 3 1967-09-01   516 199113    11.7     4.6     2958
## 4 1967-10-01   513 199311    12.5     4.9     3143
## 5 1967-11-01   518 199498    12.5     4.7     3066
## 6 1967-12-01   526 199657    12.1     4.8     3018
  • Create basic line plots
# Basic line plot
ggplot(data = economics, aes(x = date, y = pop))+
  geom_line(color = "#00AFBB", size = 2)
# Plot a subset of the data
ss <- subset(economics, date > as.Date("2006-1-1"))
ggplot(data = ss, aes(x = date, y = pop)) + 
  geom_line(color = "#FC4E07", size = 2)


  • Control line size by the value of a continuous variable:
ggplot(data = economics, aes(x = date, y = pop)) +
  geom_line(aes(size = unemploy/pop), color = "#FC4E07")



Source: STHDA, http://www.sthda.com/english/articles/32-r-graphics-essentials/128-plot-time-series-data-using-ggplot/
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.