【发布时间】:2021-08-23 15:06:00
【问题描述】:
我是 plotly 的新手,我正在尝试了解如何在 plotly 提供的更新菜单功能中设置 args 和 args2 的值(如文档 Updatemenus documentation 中所述)。
我尝试使用在 stackoverflow (Plotly: How to give different label names in a dropdown menu?) 的答案中找到的代码 sn-p。
这是修改后的代码:
# imports
import plotly.graph_objects as go
import numpy as np
# data
x = np.linspace(-np.pi, np.pi, 100)
y1 = np.sin(x)
y1b = y1-1
y2 = np.tan(x)
y2b = y2-1
# plotly setup
fig = go.Figure()
# Add one ore more traces
fig.add_traces(go.Scatter(x=x, y=y1,name='sin', visible=False, showlegend=True))
fig.add_traces(go.Scatter(x=x, y=y1b,name='sin - 1', visible=False, showlegend=True))
fig.add_traces(go.Scatter(x=x, y=y2,name='tan', visible=False, showlegend=True))
fig.add_traces(go.Scatter(x=x, y=y2b,name='tan - 1', visible=False, showlegend=True))
# construct menus
updatemenus = [{'active':-1,'buttons': [{'method': 'restyle',
'label': 'Sine',
'args': [{'y': [y1, y1b, y2, y2b],
'label':'Sine',
'name':['sin', 'sin - 1', 'tan', 'tan - 1'],
'visible': True}, [0, 1]],
'args2': [
{'visible': False}, ]
},
{'method': 'restyle',
'label': 'Tan',
'args': [{'y': [y2, y2b, y1, y1b],
'name':['tan', 'tan - 1', 'sin', 'sin - 1'],
'visible':True}, [0, 1]],
'args2': [{
'visible':False},
],
}
],
'direction': 'down',
'showactive': True,}]
# update layout with buttons, and show the figure
fig.update_layout(updatemenus=updatemenus)
fig.show()
这给了我想要实现的目标,即在我第一次单击下拉菜单中的 Sine 时显示正弦图,并在我再次单击 Sine 时清除该图(对于 Tan 也是如此)。
但是,我的问题是:
-
我在文档或其他任何地方都找不到关于传递给 args 和 args2 的内容的任何信息。您能否提供任何文档参考?
-
最后,我什至不知道如何理解 args 的行为,尤其是第一项(带有 'y' 和 'name' 键的字典)和我理解的第二项是跟踪索引列表(?)。在以下示例中,我在 Sine 和 Tan 按钮中将索引列表设置为 [2, 3]。因此,我希望通过单击 Sine 按钮来获得 Tan 图,反之亦然。但情节并没有改变。
# construct menus
updatemenus = [{'active':-1,'buttons': [{'method': 'restyle',
'label': 'Sine',
'args': [{'y': [y1, y1b, y2, y2b],
'label':'Sine',
'name':['sin', 'sin - 1', 'tan', 'tan - 1'],
'visible': True}, [2, 3]],
'args2': [
{'visible': False}, ]
},
{'method': 'restyle',
'label': 'Tan',
'args': [{'y': [y2, y2b, y1, y1b],
'name':['tan', 'tan - 1', 'sin', 'sin - 1'],
'visible':True}, [2, 3]],
'args2': [{
'visible':False},
],
}
],
'direction': 'down',
'showactive': True,}]
您能否告诉我设置这些值以定位正确跟踪的正确方法?
提前谢谢你!
【问题讨论】:
-
您可以将任何布局参数传递给 args 参数:title、yaxis、hovermode、autosize 等。
-
感谢您的回答!我尝试了布局参数,但这不起作用。我可以弄清楚 args 接受跟踪参数(我们传递给 fig.update_trace() 的那些)。见link。不过,我不明白为什么情节没有用正确的跟踪更新。这部分有什么帮助吗?再次感谢
-
@Downforu 我的解释对你有意义吗?
-
非常感谢您的详细解答!现在完全有道理了!