Animations with Plotly in Python
Data visualization is one of the highlights of data analysis as it involves a graphical representation of data. We can enhance our ability to interpret data findings greatly.
Today, we'll be demonstrating how to utilize Plotly to create captivating animations for visualizing trends over different periods of time. Let's get started!
Plotly
Plotly is a data visualization library that allows us to create rich and dynamic visualizations in Python, R, and JavaScript. Some interesting features are:
zooming
tooltips
rotating
downloading plots
Animations in Plotly
In Plotly, an animation is a dynamic visualization technique that shows the changes in data over time by rendering frames one by one and depicting the evolving patterns.
Sample scenario
Let's say we have a GDP, population, and life expectancy dataset in Plotly. We can showcase a dynamic visualization of these variables over decades easily using animations.
Dash
Dash is a Python web application framework that we can utilize in our code and render a web application depicting our animation.
This application will display an animated scatter plot depicting countries' GDP, population, and life expectancy evolution.
Basic mechanism
We'll make a callback function that first renders a loading state, and once the page loads, it retrieves data from Plotly's sample dataset. The callback then generates an animated scatter plot with frames representing changes over time.
Complete code
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
app = Dash(__name__)
app.layout = html.Div(style={'backgroundColor': 'black'}, children=[
html.H4('Animated GDP and population over decades', style={'color': 'white'}),
dcc.Loading(
id="loading",
type="cube",
children=dcc.Graph(id="graph")
)
])
@app.callback(
Output("graph", "figure"),
Input("loading", "loading_state"))
def display_animated_graph(loading_state):
df = px.data.gapminder()
return px.scatter(
df, x="gdpPercap", y="lifeExp", animation_frame="year",
animation_group="country", size="pop", color="continent",
hover_name="country", log_x=True, size_max=55,
range_x=[100, 100000], range_y=[25, 90])
if __name__ == '__main__':
app.run_server(debug=True, host="0.0.0.0", port=5000)
Code explanation
Let's break down the code into four major steps.
Importing modules
We first begin by importing the crucial modules from Dash and Plotly.
Setting up our app
We create an instance of the Dash class using
app.We define the app layout using an HTML div. This div contains a header having a title and a loading indicator. Once loaded, the animated graph is shown to us on the screen.
Callback function
We define the
@app.callbackdecorator to define a callback function nameddisplay_animated_graph.It takes an
Inputfrom the loading state of thedcc.Loadingcomponent and then returns anOutputfor thedcc.Graphcomponent.The callback function retrieves the "gapminder" dataset, i.e., Plotly's built-in dataset, using
px.data.gapminder(). This dataset can tell us about GDP, life expectancy, population, etc., over various years for different countries. We save it indf.Next, the
px.scatterfunction is used to create a scatter plot. For the data, we use thedfDataFrame.Then we animated the scatter plot using the
animation_frameparameter set to "year", which allows us to see how data changes over different years.We also set the
animation_groupto "country" to group the data by country.Parameters like
size,color,hover_name,log_x, can be customized for our plot too!
The range of range_x and range_y are used to show how much data is visible in the plot.
App
We use
if __name__ == '__main__':to ensure that this only executes when the code is run directly.The
app.run_servermethod is used to start the Dash server. You can customize your port settings accordingly.
Demonstration
Once the Dash application is run, it starts a server on the specified port and renders an interactive plot depicting the animation. We can press the play button to see the animation in action and stop it anytime using the stop button. The countries within the animation can be hovered upon, and their information can be obtained.
This is the loading cube that first renders until the dataset is loaded.
We can see the frames moving by in the animation here.
What function allows us to group data together for the animation?
Free Resources