How to Plot Multiple Series/Lines in a Time Series Using Plotly in R?
Last Updated :
06 Aug, 2024
Plotly is a powerful and flexible graphing library that enables the creation of interactive plots in R. It is especially useful for visualizing time series data with multiple lines or series. In this article, we will cover how to plot multiple time series in a single plot using Plotly in R.
Multiple Time Series
Multiple time series involve more than one time-dependent variable recorded simultaneously. Plotting multiple time series can reveal correlations and interactions between different variables over time. When dealing with multiple time series, we analyze two or more related time-dependent variables. Plotting multiple time series allows us to:
- Compare Trends: Visualize how different series evolve over time.
- Identify Correlations: Understand relationships between variables.
- Detect Anomalies: Spot unusual deviations from expected patterns.
Plotly for Time Series
Plotly is an open-source graphing library that provides tools for creating interactive visualizations. It supports various chart types, including line charts, which are ideal for time series data.
- Interactivity: Zoom, pan, and hover capabilities.
- Customization: Extensive options for customizing the appearance of plots.
- Integration: Works seamlessly with R and other languages like Python and JavaScript.
Example 1: Simple Multiple Time Series Plot
This example uses the built-in economics
dataset from the ggplot2
package to plot multiple time series.
R
install.packages("plotly")
install.packages("ggplot2")
library(plotly)
library(ggplot2)
data <- economics[, c("date", "psavert", "uempmed", "unemploy")]
colnames(data) <- c("Date", "Personal Savings Rate", "Median Duration of Unemployment",
"Number of Unemployed")
p <- plot_ly(data, x = ~Date) %>%
add_lines(y = ~`Personal Savings Rate`, name = 'Personal Savings Rate') %>%
add_lines(y = ~`Median Duration of Unemployment`,
name = 'Median Duration of Unemployment') %>%
add_lines(y = ~`Number of Unemployed`, name = 'Number of Unemployed') %>%
layout(
title = "US Economic Time Series",
xaxis = list(title = "Date"),
yaxis = list(title = "Values"),
legend = list(x = 0.1, y = 0.9)
)
p
Output:
Plot Multiple Series/Lines in a Time Series Using Plotly in RExample 2: Customizing Line Styles
This example demonstrates how to customize the line styles, including colors and widths.
R
p <- plot_ly(data, x = ~Date) %>%
add_lines(y = ~`Personal Savings Rate`, name = 'Personal Savings Rate',
line = list(color = 'blue', width = 2)) %>%
add_lines(y = ~`Median Duration of Unemployment`,
name = 'Median Duration of Unemployment',
line = list(color = 'red', width = 2)) %>%
add_lines(y = ~`Number of Unemployed`, name = 'Number of Unemployed',
line = list(color = 'green', width = 2)) %>%
layout(
title = "US Economic Time Series with Custom Line Styles",
xaxis = list(title = "Date"),
yaxis = list(title = "Values"),
legend = list(x = 0.1, y = 0.9)
)
p
Output:
Plot Multiple Series/Lines in a Time Series Using Plotly in RExample 3: Adding Markers and Hover Text
This example shows how to add markers and customize hover text for better interactivity.
R
p <- plot_ly(data, x = ~Date) %>%
add_lines(y = ~`Personal Savings Rate`, name = 'Personal Savings Rate',
line = list(color = 'blue', width = 2),
marker = list(color = 'blue', size = 5),
hoverinfo = 'text',
text = ~paste('Date:', Date, '<br>Personal Savings Rate:',
`Personal Savings Rate`)) %>%
add_lines(y = ~`Median Duration of Unemployment`,
name = 'Median Duration of Unemployment',
line = list(color = 'red', width = 2),
marker = list(color = 'red', size = 5),
hoverinfo = 'text',
text = ~paste('Date:', Date, '<br>Median Duration of Unemployment:',
`Median Duration of Unemployment`)) %>%
add_lines(y = ~`Number of Unemployed`, name = 'Number of Unemployed',
line = list(color = 'green', width = 2),
marker = list(color = 'green', size = 5),
hoverinfo = 'text',
text = ~paste('Date:', Date, '<br>Number of Unemployed:',
`Number of Unemployed`)) %>%
layout(
title = "US Economic Time Series with Markers and Hover Text",
xaxis = list(title = "Date"),
yaxis = list(title = "Values"),
legend = list(x = 0.1, y = 0.9)
)
p
Output:
Plot Multiple Series/Lines in a Time Series Using Plotly in RExample 4: Multiple Y-Axes
This example shows how to create a plot with multiple y-axes to compare series with different scales.
R
p <- plot_ly(data, x = ~Date) %>%
add_lines(y = ~`Personal Savings Rate`, name = 'Personal Savings Rate',
line = list(color = 'blue', width = 2),
yaxis = "y") %>%
add_lines(y = ~`Median Duration of Unemployment`,
name = 'Median Duration of Unemployment',
line = list(color = 'red', width = 2),
yaxis = "y2") %>%
add_lines(y = ~`Number of Unemployed`, name = 'Number of Unemployed',
line = list(color = 'green', width = 2),
yaxis = "y3") %>%
layout(
title = "US Economic Time Series with Multiple Y-Axes",
xaxis = list(title = "Date"),
yaxis = list(title = "Personal Savings Rate", side = "left"),
yaxis2 = list(title = "Median Duration of Unemployment", side = "right",
overlaying = "y"),
yaxis3 = list(title = "Number of Unemployed", side = "right", overlaying = "y",
anchor = "free", position = 0.95),
legend = list(x = 0.1, y = 0.9)
)
p
Output:
Plot Multiple Series/Lines in a Time Series Using Plotly in RConclusion
Plotly in R provides powerful tools for visualizing multiple time series. This article covered the theory behind time series plotting and demonstrated different examples of how to create interactive plots with multiple series using Plotly. By following these examples, you can effectively visualize complex time series data and gain deeper insights through interactive plots.
Similar Reads
Draw Multiple Time Series in Same Plot in R Time Series in R programming language is used to see how an object behaves over a period of time. In R, it can be easily done by the ts() function with some parameters. Time series takes the data vector and each data is connected with timestamp value as given by the user. Method 1: Using Basic R me
2 min read
Multiple Line Plots or Time Series Plots with ggplot2 in R A multiple line plot or time series plot shows how values change over time, like crime rates or sales across years. In R, we use the ggplot2 package with the geom_line() function to create these plots. By adding a third variable, we can draw separate lines for different groups, making it easy to com
3 min read
Multiple Line Plots or Time Series Plots with ggplot2 in R A multiple line plot or time series plot shows how values change over time, like crime rates or sales across years. In R, we use the ggplot2 package with the geom_line() function to create these plots. By adding a third variable, we can draw separate lines for different groups, making it easy to com
3 min read
How to Make Lines of Radar Chart Round in R Using Plotly The Radar chart is used to represent multivariate independent data graphically. It's a circular chart where each independent variable has its own axis and all those axes are merged at the center of the radar chart. It is also known as Web Chart because it looks like Spider Web. This chart is used wh
3 min read
How to Plot a Vertical Line on a Time Series Plot in Pandas When working with time series data in Pandas, it is often necessary to highlight specific points or events in the data. One effective way to do this is by plotting vertical lines on the time series plot. In this article, we will explore how to plot a vertical line on a time series plot in Pandas, co
3 min read
How to Change Line Properties in ggplot2 Halfway in a Time Series Using R In time series visualizations, it can be useful to distinguish between different segments of data by changing line properties such as color, size, or type. For example, you may want to change the line's appearance at a specific time point to highlight a change in the data. In this article, we'll dem
3 min read