Ice*_*lim 5 python pandas plotly dropdown
我正在编写一个小脚本来使用plotly 绘制材料数据,我尝试使用下拉列表来选择要显示的数据帧的哪一列。我可以通过一一定义列来做到这一点,但数据框的大小会改变,所以我想使其灵活。
我尝试了一些事情并做到了这一点;
for i in df.columns:
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df[i]))
fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
buttons=list([
dict(
args=["values", i],
label=i,
method="update"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.1,
xanchor="left",
y=1.1,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
go.layout.Annotation(text="Material:", showarrow=False,
x=0, y=1.085, yref="paper", align="left")
]
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
图表显示了 df 的最后一列,而下拉列表仅保存最后一个列标题?
我的数据看起来像这样,其中 i 是索引,图表和下拉列表显示“G”列;
i A B C D E F G
1 8 2 4 5 4 9 7
2 5 3 7 7 6 7 3
3 7 4 9 3 7 4 6
4 3 9 3 6 3 3 4
5 1 7 6 9 9 1 9
Run Code Online (Sandbox Code Playgroud)
以下建议应该正是您所要求的。不过,它不会在极端程度上超出内置功能,这意味着您已经可以通过单击图例来对图形进行子集化。无论如何,请告诉我这是否是您可以使用的东西或者是否需要一些调整。
图 1 - 第一次执行时的图状态:
点击dropdown左上角 并选择,D例如得到:
图 2 - 从下拉列表中选择后的图状态D:
代码:
# imports
import plotly.graph_objs as go
import pandas as pd
# data sample
df = pd.DataFrame({'i': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
'A': {0: 8, 1: 5, 2: 7, 3: 3, 4: 1},
'B': {0: 2, 1: 3, 2: 4, 3: 9, 4: 7},
'C': {0: 4, 1: 7, 2: 9, 3: 3, 4: 6},
'D': {0: 5, 1: 7, 2: 3, 3: 6, 4: 9},
'E': {0: 4, 1: 6, 2: 7, 3: 3, 4: 9},
'F': {0: 9, 1: 7, 2: 4, 3: 3, 4: 1},
'G': {0: 7, 1: 3, 2: 6, 3: 4, 4: 9}})
df=df.set_index('i')
# plotly figure setup
fig = go.Figure()
# one trace for each df column
for col in df.columns:
fig.add_trace(go.Scatter(x=df.index, y=df[col].values,
name = col,
mode = 'lines')
)
# one button for each df column
updatemenu= []
buttons=[]
for col in df.columns:
buttons.append(dict(method='restyle',
label=col,
args=[{'y':[df[col].values]}])
)
# some adjustments to the updatemenu
updatemenu=[]
your_menu=dict()
updatemenu.append(your_menu)
updatemenu[0]['buttons']=buttons
updatemenu[0]['direction']='down'
updatemenu[0]['showactive']=True
# update layout and show figure
fig.update_layout(updatemenus=updatemenu)
fig.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4208 次 |
| 最近记录: |