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()
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.
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.
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.
You can set up one trace and a button option for each individual trace. This will turn this figure...
... into this:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With