R How to Draw Multiple Time Series in ggplot2 Plot (Example Code)
In this R post you’ll learn how to create a plot showing multiple time series.
Preparing the Example
set.seed(7462945) # Set random seed data <- data.frame(Year = 1901:2100, # Constructing random data set TS = rep(c("TS1", "TS2", "TS3"), each = 200), Values = c(rnorm(200, 10, 5), 1:200 + runif(200, 10, 30), 1:50 + rnorm(200, 15, 30))) head(data) # Showing head of data set in console # Year TS Values # 1 1901 TS1 19.333379 # 2 1902 TS1 5.082332 # 3 1903 TS1 11.704542 # 4 1904 TS1 5.036833 # 5 1905 TS1 8.487180 # 6 1906 TS1 16.927665 |
set.seed(7462945) # Set random seed data <- data.frame(Year = 1901:2100, # Constructing random data set TS = rep(c("TS1", "TS2", "TS3"), each = 200), Values = c(rnorm(200, 10, 5), 1:200 + runif(200, 10, 30), 1:50 + rnorm(200, 15, 30))) head(data) # Showing head of data set in console # Year TS Values # 1 1901 TS1 19.333379 # 2 1902 TS1 5.082332 # 3 1903 TS1 11.704542 # 4 1904 TS1 5.036833 # 5 1905 TS1 8.487180 # 6 1906 TS1 16.927665
Example: Create Time Series Plot with ggplot2 Package
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2
ggplot(data, # ggplot2 plot of multiple time series aes(x = Year, y = Values, col = TS)) + geom_line() |
ggplot(data, # ggplot2 plot of multiple time series aes(x = Year, y = Values, col = TS)) + geom_line()
Related Tutorials
Below, you may find some further resources that are related to the content of this article: