Python / Plotly的新增功能,我正在尝试通过plotly'优化'交互式绘图
下面是df
Date AA AQ AS B6 CO DH DL EV F9 FL HA HP MQ NW OH OO TZ UA US WN XE YV DayofMonth Month
27/12 5.0 0.0 2.0 6.0 3.0 NaN 2.0 6.0 2.0 2.0 0.0 1.0 4.0 5.0 1.0 9.0 0.0 5.0 5.0 17.0 1.0 2.0 27 12
28/12 8.0 0.0 3.0 2.0 0.0 1.0 6.0 4.0 1.0 3.0 1.0 0.0 5.0 3.0 1.0 3.0 0.0 6.0 4.0 19.0 6.0 0.0 28 12
29/12 2.0 NaN 1.0 NaN 1.0 0.0 11.0 4.0 4.0 1.0 0.0 1.0 4.0 6.0 2.0 4.0 0.0 6.0 3.0 13.0 6.0 2.0 29 12
import plotly.graph_objects as go
# Initialize figure
fig = go.Figure()
df= pivot_gp.copy()
# Add Traces
for col in ['AA', 'AQ', 'AS', 'B6', 'CO', 'DH', 'DL', 'EV', 'F9', 'FL', 'HA', 'HP', 'MQ', 'NW', 'OH', 'OO', 'TZ', 'UA', 'US', 'WN', 'XE', 'YV']:
fig.add_trace(go.Scatter(x= list(df.Date), y= list(df[col]), name= f"{col}", line= dict(color="red")))
fig.update_layout(updatemenus=[dict(active= 0,
buttons=list([dict(label= "None",
method= "update",
args= [{"visible": [False, False, False, False, False, False, False, False, False, False, False,
False,False, False, False, False, False, False, False, False, False, False]}, {"title": "Unique Carriers"}]),
dict(label= "AA",
method= "update",
args= [{"visible": [True, False, False, False, False, False, False, False, False, False, False,
False,False, False, False, False, False, False, False, False, False, False]}, {"title": "Unique Carrier: AA"}]),
dict(label= "AQ",
method= "update",
args= [{"visible": [False, True, False, False, False, False, False, False, False, False, False,
False,False, False, False, False, False, False, False, False, False, False]}, {"title": "Unique Carrier: AQ"}]),
dict(label= "All",
method= "update",
args= [{"visible": [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]},
{"title": "Unique Carriers"}]),
]), ) ])
如您所见,我已经能够创建一个循环以遍历各列并在交互式绘图中添加一条线。但是,更新功能出现问题。
问题:
如何创建循环以遍历所有列并在例如以下正确列时添加True的循环:
for col in [cols]:
fig.update_layout(updatemenus=[dict(active= 0,
buttons=list([dict(label= f"{col}",
method= "update",
args= [{"visible": [True, False, False, False, False, False, False, False, False, False, False,
False,False, False, False, False, False, False, False, False, False, False]}, {"title": "Unique Carrier: f'{col}'"}]),
挑战在循环中的参数列表中:
奖金问题:只是为了使其“漂亮”,在第一个循环中,我如何更改以下各列的颜色:
line= dict(color="red")
感谢任何人的帮助!
也许可以帮助您:
1替换适用于['AA','AQ','AS','B6','CO','DH','DL','EV','F9','FL','HA','HP ','MQ','NW','OH','OO','TZ','UA','US','WN','XE','YV']]: 通过
for col in df.columns:
2要更改可见列表,您可以尝试:
"visible":[ x==col for x in df.columns]
3对于颜色,您可以设置词典:
color_dict={'AA':"red" , 'AQ':"blue" , 'AS:"green"}
line= dict(color=color_dict.get(col))