Introduction to Data Visualization with Plotly in Python
Alex Scriven
Data Scientist
An interactive element to toggle between values and update your plot
Often used for viewing data over time, such as data from different years
Can be used for any group, such as penguin islands
Ensure it makes sense in your plot
A year slider:
A penguin island slider:
plotly.express
allows sliders via the animation_frame
and animation_group
arguments
animation_frame
: What will be on the slider (Year
or Island
on previous slide)animation_group
: How to tell Plotly it is the same object over timefig = px.scatter( data_frame=revenues, y='Revenue', x='Employees', color='Industry',
animation_frame='Year', animation_group='Company')
fig.update_layout({ 'yaxis': {'range': [0, 500000]}, 'xaxis': {'range': [-100000, 2500000]} })
fig['layout'].pop('updatemenus') fig.show()
plotly.express
sliders have a key limitation - the animation
slider method
In the Figure
object
fig['layout']['sliders'][0].steps[0]['method']
animate
plotly.express
, you can't update data or layout — only animate the same data point over different 'frames'.graph_objects
to create the slider
To use graph_objects
, we need to:
Let's create the figure and add traces
fig = go.Figure()
for island in ['Torgersen', 'Biscoe', 'Dream']: df = penguins[penguins.Island == island]
fig.add_trace(go.Scatter( x=df["Culmen Length (mm)"], y=df["Culmen Depth (mm)"], mode='markers', name=island))
Let's create the slider object:
sliders = [ {'steps':[
{'method': 'update', 'label': 'Torgersen',
'args': [{'visible': [True, False, False]}]},
{'method': 'update', 'label': 'Bisco',
'args': [{'visible': [False, True , False]}]},
{'method': 'update', 'label': 'Dream',
'args': [{'visible': [False, False, True]}]}
]} ]
More formatting options available in the docs!
Now we can add the slider to our figure:
fig.update_layout({'sliders': sliders})
fig.show()
The first screen was a bit funny huh? Let's fix that!
We can fix the initial display by setting only the relevant traces to show.
# Make traces invisible fig.data[1].visible=False fig.data[2].visible=False
fig.update_layout({'sliders': sliders}) fig.show()
Much better!
Introduction to Data Visualization with Plotly in Python