Animate Interactive plotly Graph in R (4 Examples)

 

Hi! This tutorial will show you how to animate interactive plotly graphs in the R programming language.

First, though, here is an overview of this tutorial:

Let’s dive into the R code!

 

Install & Load plotly & dplyr Libraries

First, we will install and load both plotly and dplyr R libraries.

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

Dplyr is the foremost data manipulation and analysis library in R, and it enables the use of the pipe operator to pipe lines of code together, so that they can be run in one chunk.
 

Create Sample Data Frame

Here, we will create our sample dataset. For this tutorial, we will make use of the gapminder dataset. If you are coding in the R Studio IDE, the gapminder dataset package can be easily installed and loaded in your R programming environment by running the code below.

# install gapminder package
install.packages("gapminder")
 
# load gapminder package
library(gapminder)

However, if you are coding in another code editor, you can download the gapminder dataset from an online datasets repository, such as Kaggle.

You can preview the first 10 rows of the dataset by running:

df <- gapminder
head(df,10)
 
 #     country  continent  year  lifeExp   pop  gdpPercap
 #1 Afghanistan Asia       1952    28.8  8425333      779.
 #2 Afghanistan Asia       1957    30.3  9240934      821.
 #3 Afghanistan Asia       1962    32.0 10267083      853.
 #4 Afghanistan Asia       1967    34.0 11537966      836.
 #5 Afghanistan Asia       1972    36.1 13079460      740.
 #6 Afghanistan Asia       1977    38.4 14880372      786.
 #7 Afghanistan Asia       1982    39.9 12881816      978.
 #8 Afghanistan Asia       1987    40.8 13867957      852.
 #9 Afghanistan Asia       1992    41.7 16317921      649.
#10 Afghanistan Asia       1997    41.8 22227415      635.

 

Example 1: Make Multiple Trace Animation

In this first example, we will create a multiple trace animation, where we will build a scatter plot of life expectancy and gdp per capita, and visualize the changes over time in an animation.

fig <- df |> 
  plot_ly(x = ~gdpPercap,
          y = ~lifeExp,
          size = ~pop,
          color = ~continent,
          frame = ~year,
          text = ~country,
          hoverinfo = "text",
          type = "scatter",
          mode = "markers") |> 
  layout(xaxis = list(type = "log"))
 
 
fig


In the plot_ly() function, we plotted gdp per capita on the X axis and life expectancy on the Y axis. We then sized the points by population, and parsed year to the frame = argument. This creates the frames needed for the transition in the animation.
 

Example 2: Make Multiple Trace Animation with Different Animation Options

In this second example, we will build the same visualization, but we will add animation options that will modify the frames’ transition.

fig <- df |> 
  plot_ly(x = ~gdpPercap,
          y = ~lifeExp,
          size = ~pop,
          color = ~continent,
          frame = ~year,
          text = ~country,
          hoverinfo = "text",
          type = "scatter",
          mode = "markers") |> 
  animation_opts(frame = 1000,
                 easing = "quad",
                 redraw = F) |> 
  layout(xaxis = list(type = "log"))
 
 
fig


Here, we introduced the animation_opts() function, wherein we defined 3 arguments. The frame = argument refers to the amount of time between the frames in milliseconds. The easing = argument refers to the type of transition that occurs between the frames. There are many easing options, such as “quad”, “cubic”, “elastic”, and “sin”. We also set the redraw = argument to false, because we do not want a redraw of the plot at the completion of the transition.
 

Example 3: Make Multiple Trace Animation with Button

In this third example, we are going to add a button to our animation, and place it on the right-hand side of the plot. We will not need to re-write the entire code chunk; we will only add a new function to the existing plotly object.

fig <- fig |> 
  animation_button(x = 1,xanchor = "right",
                   y = 0,yanchor = "bottom") 
 
fig


We piped to our existing plotly fig object the animation_button() function, which we used to create a button. Inside the function, we set the coordinates for the button, and defined its anchor positions.
 

Example 4: Make Multiple Trace Animation with Slider

In this fourth and final example, we will add a slider to our animation.

fig <- fig |> 
  animation_slider(currentvalue = list(prefix = "YEAR: ", font = list(color="blue")))
 
fig


In the above code, we added the animation_slider() function to the existing plotly fig object. In the function, we set the label prefix for the slider as “YEAR”, and colored the font blue.

 

Video, Further Resources & Summary

Do you need more explanations on how to animate interactive plotly graphs in R? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain in some more detail how to animate interactive plotly graphs in R.

 

The YouTube video will be added soon.

 Chart

With that, we have demonstrated in this tutorial how to animate interactive plotly graphs in R, as well as the customizations that can be made to the animation. I hope you found it helpful!

This post has shown how to animate interactive plotly graphs in R. 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.

Top