Adding Customised Sliders
Learn what sliders are and how to use them in Plotly to subset data and add interactivity.
Our data
Here we explore the baseball
dataset that contain important statistics in the columns seen below:
# Import librariesimport pandas as pdimport numpy as np# Import datasetsbaseball = pd.read_csv('/usr/local/csvfiles//regular_season_batting.csv')print(baseball.head())
Custom sliders in Plotly Express
When creating a custom slider in Plotly Express, we can use the animation_frame
argument, which sets the slider values to the corresponding pandas series.
In this example, we plot a baseball player’s Batting Average
against their On Base Percentage
. We then set the animation_frame
to "Year"
to accentuate that we wish to have slider values for each year so that we can observe how the dispersion of the data in a bivariate sense changes over time.
We have also allowed some extra hover information to be shown and have set the range_x
and range_y
as a list with the minimum and maximum x and y bounds, respectively.
# Import librariesimport pandas as pdimport numpy as npimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplots# Import datasetsbaseball = pd.read_csv('/usr/local/csvfiles/batting_stats.csv')# Set our marginmargin = 0.01# Create figurefig = px.scatter(baseball, x='On Base Percentage', y='Batting Average',animation_frame="Year",color_discrete_sequence=['black'],hover_name='Name',hover_data=['On Base Percentage', 'Batting Average', 'Year', 'Position'],# Here we ensure that all scatter points get shown for each year (so that none are snipped off the graph)range_x=[baseball['On Base Percentage'].min() - margin, baseball['On Base Percentage'].max() + margin],range_y=[baseball['Batting Average'].min() - margin,baseball['Batting Average'].max() + margin])# Set marker size the plotly express wayfig.update_traces(marker_size=12)fig.update_layout(title='On Base Percentage vs Batting Average')# Showfig.show()
Removing animation functionality
By running the following code, we notice that the type of our Plotly Express figure is that of plotly.graph_objs._figure.Figure
.
type(fig)
We get the following:
plotly.graph_objs._figure.Figure
With these figure objects, we can then observe certain aspects of our graph, one being the complete "layout"
of our figure, which we can then observe with dictionary-like syntax.
The output for this is quite large, but the key is noted below:
'updatemenus': [{'buttons': [{'args': [None,
...