Lesson
Sliders and buttons
Learn Sliders and buttons in SQLPad's Data Science in Action course with practical examples and guided lessons.
In this lesson, we will learn about two interactive features in Plotly: sliders and buttons. Both of these features allow users to interact with the visualizations and manipulate the data being displayed. We will go through examples that demonstrate how to create sliders and buttons using built-in datasets from Plotly and pandas.
Sliders
Sliders are a great way to allow users to interactively explore different aspects of a dataset by adjusting a value or a range of values. In Plotly, sliders can be easily added to a plot using the updatemenus attribute.
Let's start with an example using the famous Iris dataset. We will create a scatter plot showing the relationship between sepal length and width, and we will add a slider to filter the data based on the petal length.
import plotly.express as px
# Load the Iris dataset
iris = px.data.iris()
max_petal_length = int(iris["petal_length"].max()) + 1
# Create a scatter plot with animations
fig = px.scatter(iris,
x='sepal_width',
y='sepal_length',
color='species',
animation_frame=iris["petal_length"].apply(lambda x: min(int(x)+1, max_petal_length)).astype(str),
animation_group="species",
range_y=[iris["sepal_length"].min(), iris["sepal_length"].max()],
range_x=[iris["sepal_width"].min(), iris["sepal_width"].max()],
title='Iris Sepal Width vs Sepal Length'
)
# Update layout
fig.update_layout(
updatemenus=[dict(
type="buttons",
direction="left",
pad={"r": 10, "t": 87},
showactive=False,
x=0.1,
xanchor="right",
y=0,
yanchor="top"
)],
)
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 1000
fig.show()
In the example above, we first create a scatter plot using px.scatter() and then add a slider to the plot using the update_layout() function. The updatemenus attribute accepts a list of dictionaries, where each dictionary represents a slider or a button. In this case, we are creating a slider that filters the data based on the petal length, and we set the slider range from 1 to 6 with steps of 1.
Buttons
Buttons can be used to trigger specific actions or updates on a plot. Similar to sliders, buttons can be added to a plot using the updatemenus attribute.
Let's create an example using the Gapminder dataset. We will create a scatter plot showing the relationship between life expectancy and GDP per capita, and we will add buttons to filter the data based on the continent.
import plotly.graph_objs as go
gapminder = px.data.gapminder()
continent_list = gapminder["continent"].unique()
fig = go.Figure()
# Create a scatter plot for each continent
for continent in continent_list:
fig.add_trace(go.Scatter(
x=gapminder[gapminder["continent"]==continent]['gdpPercap'],
y=gapminder[gapminder["continent"]==continent]['lifeExp'],
mode='markers',
name=continent
))
# Define buttons for continent filtering
buttons = [dict(label=continent,
method="update",
args=[{"visible": [cont == continent for cont in continent_list]}])
for continent in continent_list]
# Add "All" button
buttons.append(dict(label="All",
method="update",
args=[{"visible": [True for cont in continent_list]}]))
fig.update_layout(
title='Life Expectancy vs GDP per Capita',
updatemenus=[dict(
type="buttons",
direction="down",
buttons=buttons
)]
)
fig.show()
In this example, we first create a scatter plot using px.scatter() and then add buttons to the plot using the update_layout() function. We create a list of visible data points for each button, and then we create the buttons by passing a list of dictionaries to the buttons attribute. Each dictionary represents a button and contains a label, a method (in this case, "update"), and arguments that define the action of the button (in this case, updating the data visibility).
Conclusion
In this lesson, we learned how to create sliders and buttons in Plotly to make our visualizations more interactive. These features allow users to explore the data in more depth and can be easily added to any plot using the updatemenus attribute. Keep in mind that sliders and buttons are just two examples of the many interactive features available in Plotly, and you can further customize your plots by combining these elements with other interactive features.
Exercises
1. Sliders and Buttons in Plotly
Instruction
Create a scatter plot using the Gapminder dataset showing the relationship between life expectancy and GDP per capita. Add buttons to filter the data based on the continent.
My Solution
# Your solution goes here
Hint
- Load the Gapminder dataset using
px.data.gapminder(). - Create a scatter plot using
px.scatter()withx='gdpPercap',y='lifeExp', andcolor='continent'. - Prepare a list of visible data points for each button by iterating through the unique continents in the dataset.
- Add buttons to the plot using the
update_layout()function and theupdatemenusattribute. - Use a list comprehension to create the buttons with the appropriate labels, methods, and arguments.
- Display the plot using
fig.show().
Solution
import plotly.graph_objs as go
gapminder = px.data.gapminder()
continent_list = gapminder["continent"].unique()
fig = go.Figure()
# Create a scatter plot for each continent
for continent in continent_list:
fig.add_trace(go.Scatter(
x=gapminder[gapminder["continent"]==continent]['gdpPercap'],
y=gapminder[gapminder["continent"]==continent]['lifeExp'],
mode='markers',
name=continent
))
# Define buttons for continent filtering
buttons = [dict(label=continent,
method="update",
args=[{"visible": [cont == continent for cont in continent_list]}])
for continent in continent_list]
# Add "All" button
buttons.append(dict(label="All",
method="update",
args=[{"visible": [True for cont in continent_list]}]))
fig.update_layout(
title='Life Expectancy vs GDP per Capita',
updatemenus=[dict(
type="buttons",
direction="down",
buttons=buttons
)]
)
fig.show()