Draw Multiple Time Series in Same Plot in R | Using Base R & ggplot2 | lines & geom_line Functions

Published 2021-04-09
How to draw multiple time series in the same plot in the R programming language. More details: statisticsglobe.com/draw-multiple-time-series-in-s…
R code of this video:

set.seed(1023172) # Create random example data
data <- round(data.frame(year = 2001:2025,
ts1 = 1:25 + rnorm(25),
ts2 = 30:6 + runif(25, 0, 10),
ts3 = rnorm(25, 5, 5)))

plot(data$year, # Draw first time series
data$ts1,
type = "l",
col = 2,
ylim = c(- 15, 40),
xlab = "Year",
ylab = "Values")
lines(data$year, # Draw second time series
data$ts2,
type = "l",
col = 3)
lines(data$year, # Draw third time series
data$ts3,
type = "l",
col = 4)
legend("topright", # Add legend to plot
c("ts1", "ts2", "ts3"),
lty = 1,
col = 2:4)

install.packages("reshape2") # Install reshape2 package
library("reshape2") # Load reshape2 package

data_long <- melt(data, id.vars = "year") # Reshaping data to long format

install.packages("ggplot2") # Install ggplot2 package
library("ggplot2") # Load ggplot2 package

ggplot(data_long, # Draw ggplot2 time series plot
aes(x = year,
y = value,
col = variable)) +
geom_line()

Follow me on Social Media:
Facebook: www.facebook.com/statisticsglobecom/
LinkedIn: www.linkedin.com/company/statisticsglobe/
Patreon: www.patreon.com/statisticsglobe
Pinterest: www.pinterest.de/JoachimSchork
Reddit: www.reddit.com/user/JoachimSchork
Twitter: twitter.com/JoachimSchork

All Comments (10)
  • @shirleyxiao2420
    Thank you sooooo much for making a series of videos of high quality. I am s student who is learning R recently, I find your channel is one of the most helpful channels as aspect of the R language. I learned a lot from your videos to deal with the real-life problem I encountered. Thank you!
  • I am currently trying to learn R, and this video was exactly what I needed. Thank you for all you do!
  • Dear Sir Joaquim, your tutorials are awesome, very informative and well detailed including at your web site. Keep it up.
  • @bryan1995ism
    Thanks, what a great info, you have a new suscriber. Cheers ¡¡
  • @alibayat2914
    Thank you so much. what if the length of the two data was different?