Lesson

Animation

Learn Animation in SQLPad's Data Science in Action: Interactive Visualization with Plotly and Pandas course with practical examples and guided lessons.

In this lesson, we will learn about the animation capabilities of Plotly, which allow you to create interactive and dynamic visualizations. Animation is a powerful feature that can help you communicate complex patterns or trends in your data effectively.

Animating Scatter Plots

Let's start by creating an animated scatter plot using the Gapminder dataset. This dataset contains information about the GDP per capita, life expectancy, and population of different countries for various years.

import plotly.express as px

data = px.data.gapminder()

fig = px.scatter(data_frame=data,
                 x="gdpPercap",
                 y="lifeExp",
                 size="pop",
                 color="continent",
                 log_x=True,
                 hover_name="country",
                 animation_frame="year",
                 range_y=[20, 90])                 

fig.update_layout(title="GDP per Capita vs. Life Expectancy (1952-2007)",  template='plotly_dark')
fig.show()

In this example, we use the animation_frame parameter to specify the column in the DataFrame that will be used to create the animation frames (in this case, the "year" column). The range_y parameter sets the y-axis range to be constant throughout the animation.

Animating Line Plots

You can also create animated line plots using Plotly. Let's create a line plot of the global temperature anomaly over time using the animation module in Plotly.

import plotly.graph_objs as go
import pandas as pd
import pyodide.http
data = pd.read_csv(pyodide.http.open_url('https://raw.githubusercontent.com/plotly/datasets/master/2016-weather-data-seattle.csv'))

data['Month'] = pd.to_datetime(data['Date']).dt.strftime('%b')

fig = go.Figure()

for month in data['Month'].unique():
    fig.add_trace(go.Scatter(x=data['Date'][data['Month'] == month],
                             y=data['Mean_TemperatureC'][data['Month'] == month],
                             name=month,
                             visible=False))

fig.data[0].visible = True

steps = []
for i in range(len(fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(fig.data)},
              {"title": f"Temperature Anomaly in Seattle: {data['Month'].unique()[i]}"}],
        label=data['Month'].unique()[i],
    )
    step["args"][0]["visible"][i] = True
    steps.append(step)

sliders = [dict(
    active=0,
    currentvalue={"prefix": "Month: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(sliders=sliders,  template='plotly_dark')
fig.show()

In this example, we first create a line plot for each month, setting the visible attribute to False for all except the first one. Then, we create a slider with steps that update the visibility of each line plot, allowing the user to interactively explore the data.

Customizing Animation Options

You can customize the animation options using the animation attribute in the update_layout method. For example, you can change the duration and easing of the animation.

import plotly.express as px

data = px.data.gapminder()

fig = px.scatter(data_frame=data,
                 x="gdpPercap",
                 y="lifeExp",
                 size="pop",
                 color="continent",
                 log_x=True,
                 hover_name="country",
                 animation_frame="year",
                 range_y=[20, 90])

fig.update_layout(
    title="GDP per Capita vs. Life Expectancy (1952-2007)",
    template='plotly_dark',
    updatemenus=[
        dict(
            type="buttons",
            showactive=False,
            buttons=[
                dict(label="Play",
                     method="animate",
                     args=[None, {"frame": {"duration": 500, "redraw": True}}])
            ]
        )
    ]
)

fig.show()

In this example, we added a "Play" button to the scatter plot animation and set the animation duration to 500 milliseconds. You can experiment with different animation options to create the desired effect for your visualizations.

Conclusion

In this lesson, we have learned how to create animated visualizations using Plotly. Animation is a powerful feature that can help you communicate complex patterns or trends in your data effectively. You can customize the animation options and even create interactive sliders to allow users to explore your data.

Exercises

1. Animating Scatter Plots with Plotly

Instruction

Create an animated scatter plot using the Gapminder dataset to visualize the relationship between GDP per capita and life expectancy over time. Use the animation_frame parameter to create the animation frames based on the 'year' column.

My Solution

# Your solution goes here

Hint

  1. Import the plotly.express module as px.
  2. Load the Gapminder dataset using px.data.gapminder().
  3. Create a scatter plot using px.scatter() with the following parameters:
  4. data_frame: the Gapminder dataset
  5. x: 'gdpPercap'
  6. y: 'lifeExp'
  7. size: 'pop'
  8. color: 'continent'
  9. log_x: True
  10. hover_name: 'country'
  11. animation_frame: 'year'
  12. range_y: [20, 90]
  13. Update the layout of the plot with a title using fig.update_layout().
  14. Display the plot using fig.show().

Solution

import plotly.express as px

data = px.data.gapminder()

fig = px.scatter(data_frame=data,
                 x="gdpPercap",
                 y="lifeExp",
                 size="pop",
                 color="continent",
                 log_x=True,
                 hover_name="country",
                 animation_frame="year",
                 range_y=[20, 90])

fig.update_layout(title="GDP per Capita vs. Life Expectancy (1952-2007)")
fig.show()