Lesson

Dropdowns

Learn Dropdowns 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 how to add dropdowns to our interactive Plotly charts. Dropdowns allow users to select different options and update the chart accordingly without having to modify the code. This can be particularly useful when you want to display multiple datasets or chart types within a single visualization.

Setup

Before we begin, let's import the necessary libraries and load the built-in dataset from Plotly.

import plotly.express as px
import plotly.graph_objects as go

# Load built-in dataset
data = px.data.gapminder()

Creating a Dropdown

To demonstrate how to create a dropdown, we will create a scatter chart showing the relationship between life expectancy and GDP per capita for different continents.

First, let's create a scatter chart for one of the continents, say "Asia", and add a dropdown that allows us to select other continents.


# Filter data for Asia
asia_data = data[data['continent'] == 'Asia']

# Create scatter chart for Asia
fig = go.Figure(go.Scatter(x=asia_data['gdpPercap'],
                           y=asia_data['lifeExp'],
                           mode='markers',
                           text=asia_data['country'],
                           marker=dict(color=asia_data['year'],
                                       colorscale='Viridis',
                                       showscale=True)))

# Add dropdown
fig.update_layout(
    updatemenus=[
        go.layout.Updatemenu(
            buttons=[
                dict(
                    args=[{'visible': [True], 'marker.color': [asia_data['year']]}],
                    label='Asia',
                    method='update'
                ),
                dict(
                    args=[{'visible': [False]}],
                    label='Hide',
                    method='update'
                )
            ],
            direction='down',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0.1,
            xanchor='left',
            y=1.1,
            yanchor='top'
        )
    ]
)

fig.show()

In the code above, we first created a scatter chart for Asia and then added a dropdown menu with two buttons: "Asia" and "Hide". The "Asia" button will display the scatter chart, while the "Hide" button will hide it.

Now, let's add more options to the dropdown, allowing users to select other continents.

import plotly.graph_objects as go
import plotly.express as px

# Get gapminder data
data = px.data.gapminder()

# Create scatter charts for each continent
fig = go.Figure()

# Create a list of unique continents
continents = data['continent'].unique()

for continent in continents:
    filtered_data = data[data['continent'] == continent]
    fig.add_trace(go.Scatter(x=filtered_data['gdpPercap'],
                             y=filtered_data['lifeExp'],
                             mode='markers',
                             text=filtered_data['country'],
                             marker=dict(color=filtered_data['year'],
                                         colorscale='Viridis',
                                         showscale=True),
                             name=continent,
                             visible=False))

# Set the first trace to be visible by default
fig.data[0].visible = True

# Create buttons for the dropdown menu
buttons = []
for i, continent in enumerate(continents):
    visible = [False]*len(continents)
    visible[i] = True  # Toggle i'th trace to "visible"
    buttons.append(dict(
        args=[{'visible': visible}],
        label=continent,
        method='update'
    ))

# Add dropdown menu
fig.update_layout(
    updatemenus=[
        go.layout.Updatemenu(
            buttons=buttons,
            direction='down',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0.1,
            xanchor='left',
            y=1.1,
            yanchor='top'
        )
    ]
)

fig.show()

In the code above, we created scatter charts for each continent and added them to the figure using the .add_trace() method. We then created a list of buttons for the dropdown menu, setting the visible argument based on the index of the selected continent. Finally, we added the dropdown menu to the figure using the update_layout() method.

Now, when you click on the dropdown, you can select different continents to display their respective scatter charts.

Conclusion

In this lesson, we learned how to add dropdowns to our interactive Plotly charts, allowing users to select different options and update the chart accordingly. This can be particularly useful when you want to display multiple datasets or chart types within a single visualization. You can further customize the appearance and behavior of the dropdowns to fit your specific needs.

Exercises

1. Adding Dropdowns to Interactive Plotly Charts

Instruction

In this exercise, you will create a scatter chart showing the relationship between life expectancy and GDP per capita for different continents. You will then add a dropdown menu that allows users to select different continents and update the chart accordingly.

My Solution

# Your solution goes here

Hint

  1. Create a scatter chart for each continent using a for loop and the .add_trace() method.
  2. Set the first trace to be visible by default.
  3. Create a list of buttons for the dropdown menu, setting the visible argument based on the index of the selected continent.
  4. Add the dropdown menu to the figure using the update_layout() method.

Solution

import plotly.graph_objects as go
import plotly.express as px

# Get gapminder data
data = px.data.gapminder()

# Create scatter charts for each continent
fig = go.Figure()

# Create a list of unique continents
continents = data['continent'].unique()

for continent in continents:
    filtered_data = data[data['continent'] == continent]
    fig.add_trace(go.Scatter(x=filtered_data['gdpPercap'],
                             y=filtered_data['lifeExp'],
                             mode='markers',
                             text=filtered_data['country'],
                             marker=dict(color=filtered_data['year'],
                                         colorscale='Viridis',
                                         showscale=True),
                             name=continent,
                             visible=False))

# Set the first trace to be visible by default
fig.data[0].visible = True

# Create buttons for the dropdown menu
buttons = []
for i, continent in enumerate(continents):
    visible = [False]*len(continents)
    visible[i] = True  # Toggle i'th trace to "visible"
    buttons.append(dict(
        args=[{'visible': visible}],
        label=continent,
        method='update'
    ))

# Add dropdown menu
fig.update_layout(
    updatemenus=[
        go.layout.Updatemenu(
            buttons=buttons,
            direction='down',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0.1,
            xanchor='left',
            y=1.1,
            yanchor='top'
        )
    ]
)

fig.show()