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

Example: Create Time Series Plot with ggplot2 Package

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()

r graph figure 1 r draw multiple time series ggplot2 plot

Related Tutorials

Below, you may find some further resources that are related to the content of this article:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top