Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to filter a pandas dataframe using a dropdown menu?

I have a dataframe and using plotly I want to visualise the data. I have the following code

fig = px.line(df, x="row_num", y="audienceWatchRatio", color='vid_id')
fig.show() 

enter image description here

It's really messy, so I want a drop-down menu where the user can just select the vid_id and it only shows the 1 graph.

like image 401
Bryce Ramgovind Avatar asked Dec 19 '19 08:12

Bryce Ramgovind


People also ask

What is dropdown filter?

Dropdown filter presents filter values as a drop-down list. Dropdown filter's values can be loaded from a database table or manually added, and they follow the key - value form.

How do you make an interactive dropdown in Jupyter?

Data Setup for the DropdownCreate a variable confirmed_global , and store the data into covid19_confirmed using Panda's read_csv. We set the index column to Country/Region and display the dataframe. There are 266 rows. This has Country/Region in index and Lat , Long , and dates on the label.


1 Answers

You can set up one trace and a button option for each individual trace. This will turn this figure...

enter image description here

... into this:

enter image description here

The button option A will be replaced with the first column in your dataframe. And the dropdown menu will let you choose which column to display in your figure.

Code:

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import datetime

# mimic OP's datasample

NPERIODS = 200

np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10, 12, size=(NPERIODS, 4)),
                  columns=list('ABCD'))
datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),
                         periods=NPERIODS).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum()

# # plotly
fig = go.Figure()

# set up ONE trace
fig.add_trace(go.Scatter(x=df.index,
                         y=df[df.columns[0]],
                         visible=True)
             )

updatemenu = []
buttons = []

# button with one option for each dataframe
for col in df.columns:
    buttons.append(dict(method='restyle',
                        label=col,
                        visible=True,
                        args=[{'y':[df[col]],
                               'x':[df.index],
                               'type':'scatter'}, [0]],
                        )
                  )

# some adjustments to the updatemenus
updatemenu = []
your_menu = dict()
updatemenu.append(your_menu)

updatemenu[0]['buttons'] = buttons
updatemenu[0]['direction'] = 'down'
updatemenu[0]['showactive'] = True

# add dropdown menus to the figure
fig.update_layout(showlegend=False, updatemenus=updatemenu)
fig.show()
like image 62
vestland Avatar answered Sep 21 '22 18:09

vestland