Draw Time Series in plotly Graph in R (3 Examples)


Hi! This tutorial will show you how to draw a plotly time series graph in the R programming language.

Here is an overview:

Let’s jump into the R code!


Install & Load plotly & dplyr

To install and load the R plotly library and dplyr, run the lines of code below in your preferred R programming IDE or code editor:

# install plotly & dplyr
install.packages(c("plotly", "dplyr"))
# load plotly & dplyr

The R dplyr library is the foremost library for data analysis and manipulation in the R programming language. It also enables us to make use of the pipe operator (|>) to pipe several lines of code together and run them as a chunk.

So, with plotly and dplyr installed and loaded into our R programming environment, we can now use both libraries in our project. However, we need time series data to visualize.


Create Example Data

We will now create the example dataset that we will use to draw a plotly time series graph. We will fetch the data via Quantmod API and preview the first 10 rows of the dataframe:

           from = "2021-01-01",
           to = "2022-12-31")
stock <- data.frame(AAPL$AAPL.Adjusted)
stock$AAPL.Adjusted <- stock$AAPL.Adjusted/stock$AAPL.Adjusted[1]
stock <- data.frame(stock,rownames(stock))
colnames(stock) <- append("AAPL","date")
stock |> head(10)
#               AAPL       date
#2021-01-04 1.0000000 2021-01-04
#2021-01-05 1.0123636 2021-01-05
#2021-01-06 0.9782857 2021-01-06
#2021-01-07 1.0116681 2021-01-07
#2021-01-08 1.0204000 2021-01-08
#2021-01-11 0.9966770 2021-01-11
#2021-01-12 0.9952859 2021-01-12
#2021-01-13 1.0114364 2021-01-13
#2021-01-14 0.9961361 2021-01-14
#2021-01-15 0.9824586 2021-01-15

Here, we used the quantmod library to retrieve historical stock price data for Apple Inc. (AAPL) from January 1, 2021, to December 31, 2022.

Then, we created a dataframe named stock with the adjusted closing prices of AAPL and normalized the prices by dividing each price by the initial price on January 1, 2021.

Finally, we added a date column to the dataframe and renamed the columns to ‘AAPL’ and ‘date’ for further analysis or visualization.

So, with the example dataset loaded, we can now build a plotly time series graph.

Example 1: Build Time Series Graph

In this first example, we will build a basic time series graph:

fig <- stock |> 
  plot_ly(type = "scatter",mode = "lines",width = 900) |> 
  add_trace(x = ~date,y = ~AAPL, name = "AAPL") |> 
  layout(showlegend = FALSE,
         xaxis = list(zerolinecolor = "#ffff",
                      zerolinewidth = 2,
                      gridcolor = "#ffff"),
         yaxis = list(zerolinecolor = "#ffff",
                      zerolinewidth = 2,
                      gridcolor = "#ffff"),
         plot_bgcolor = "white")
options(warn = -1)

In the above example, we used the plot_ly() function to specify that we want a scatter plot with lines connecting the data points.

We also set the width of the plot to 900 pixels. The add_trace() function added the actual data to the plot, specifying the x-axis as the date column and the y-axis as the AAPL column, labeling it as “AAPL”.

The layout() function was used to customize the plot’s appearance, removing the legend, and adjusting the axis properties like color, width, and gridlines, and also setting the plot background color to white.

The options(warn = -1) line suppressed warnings, and the plot was then displayed by calling fig.


Example 2: Customize Date Range in Time Series Graph

In this second example, we will customize the date range of the x axis of the graph:

fig <- stock |> 
  plot_ly(type = "scatter", mode = "lines", width = 900) |> 
  add_trace(x = ~date,y = ~AAPL, name = "AAPL") |> 
  layout(showlegend = FALSE,
         xaxis = list(range = c("2021-03-1","2022-03-31")),
         plot_bgcolor = "white")
options(warn = -1)

In this example, we made a slight modification to the code chunk from the previous example by passing a vector of dates to the xaxis argument of the layout() function.

The vector simply contained two dates ranging from the 1st of March 2021 to the 31st of March 2022. That way, we have specified or customized the date range of the graph’s xaxis.

Example 3: Add Range Slider to Time Series Graph

In this last example, we will add a range slider to the graph:

fig <- stock |> 
  plot_ly(type = "scatter",mode = "lines",width = 900) |> 
  add_trace(x = ~date,y = ~AAPL, name = "AAPL") |> 
  layout(showlegend = FALSE,
         xaxis = list(range = c("2021-03-1","2022-03-31"),
                      rangeslider = list(visible = T)),
         plot_bgcolor = "white")
options(warn = -1)

Here, we incorporated a range slider in the plot by simply making the range slider visible on the xaxis. That way, you can skim through time and observe changes in the data over time.


Video, Further Resources & Summary

Do you need more explanations on how to draw a plotly time series graph in R? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to draw a plotly time series graph in R in some more detail.


The YouTube video will be added soon.


As you can see, it is easy to visualize time series data interactively with plotly in the R programming language. If you would like to explore other plotly visualization kinds in R, then you can have a look at these other tutorials on Statistics Globe:

This post has shown how to draw a plotly time series graph in R. I hope you found it helpful! In case you have further questions, you may leave a comment below.


R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.