我有这个简单的数据框。
import requests
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import seaborn as sns
# Intitialise data of lists
data = [{'Month': '2020-01-01', 'Expense':1000, 'ID':'123'},
{'Month': '2020-02-01', 'Expense':3000, 'ID':'123'},
{'Month': '2020-03-01', 'Expense':2000, 'ID':'123'},
{'Month': '2020-01-01', 'Expense':3000, 'ID':'456'},
{'Month': '2020-02-01', 'Expense':5000, 'ID':'456'},
{'Month': '2020-03-01', 'Expense':10000, 'ID':'456'},
{'Month': '2020-03-01', 'Expense':5000, 'ID':'789'},
{'Month': '2020-04-01', 'Expense':2000, 'ID':'789'},
{'Month': '2020-05-01', 'Expense':3000, 'ID':'789'}]
df = pd.DataFrame(data)
df
基于 ID 列中的唯一 ID,我正在尝试创建一个下拉控件。
# uniques = df['ID'].unique()
# for i in uniques:
# print(i)
我正在测试这段代码,它看起来非常接近,但它实际上并没有为我生成图表。
uniques = df['ID'].unique()
# 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 i in uniques:
#print(i)
#df_single = df[df['ID']==i]
#data=df_single
#print(data)
buttons.append(dict(method='restyle',
label=i,
visible=True,
args=[{'y':[df['ID']==i],
'x':[df.index],
'type':'scatter'}]
)
)
# 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()
我为此利用了两种资源。
https://plotly.com/python/dropdowns/
知道我做错了什么吗?
这似乎可以解决问题。
df_test = df.pivot(index='Month', columns='ID', values='Expense')
# plotly
fig = go.Figure()
# set up ONE trace
fig.add_trace(go.Scatter(x=df_test.index,
y=df_test[df_test.columns[0]],
visible=True)
)
updatemenu = []
buttons = []
# button with one option for each dataframe
for i in df_test.columns:
print(i)
buttons.append(dict(method='restyle',
label=i,
visible=True,
args=[{'y':[df_test[i]],
'x':[df_test.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()