本文介绍了Plotly:如何在下拉菜单中给出不同的标签名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习情节下拉菜单时偶然发现了一个标签问题.

I was learning plotly dropdown menu and stumbled on a label problem.

  • 选择 Sine 时如何显示标签 sin 和 sin-1.并在选择 Tan 时显示标签 tan 和 tan-1?
  • How to show labels sin and sin-1 when selected Sine. And show labels tan and tan-1 when selected Tan?
# 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'))
fig.add_traces(go.Scatter(x=x, y=y1b,name='sin - 1'))

fig.add_traces(go.Scatter(x=x, y=y2,name='tan'))
fig.add_traces(go.Scatter(x=x, y=y2b,name='tan - 1'))

# construct menus
updatemenus = [{'buttons': [{'method': 'update',
                             'label': 'Sine',
                             'args': [{'y': [y1, y1b]},]
                              },
                            {'method': 'update',
                             'label': 'Tan',
                             'args': [
                                 {'y': [y2, y2b],'label':['a','b']},
                             ]}
                           ],
                'direction': 'down',
                'showactive': True,}]

# update layout with buttons, and show the figure
fig.update_layout(updatemenus=updatemenus)
fig.show()

输出

推荐答案

这是您可以使用的通用辅助函数:

# Helper functions to create the appropriate buttons
def makePlotButtons(options, nTracesPerOption=1):    
    buttons = []
    for i, opt in enumerate(options):
        visibleArr = np.full((nTracesPerOption*len(options),), 
                             False, dtype=bool)
        
        startIdx = nTracesPerOption*i
        for idx in range(nTracesPerOption):
            visibleArr[startIdx + idx] = True
            
        buttons.append(dict(label=str(opt),
                            method='restyle',
                            args=[{'visible': list(visibleArr)}]))    # 'Visible' arg determines which plots are shown 
                                                                      # depending on which dropdown is selected 
    return buttons

其中 options 是字符串列表,nTracesPerOption 是每个选项的跟踪数.对于您的问题,您的 options 参数将为 ['Sine', 'Tan'] 并且 nTracesPerOption 为 2(例如对于 sin和罪 - 1).

where options is a list of strings and nTracesPerOption is how many traces you have per option. In the case of your questions, your options parameter would be ['Sine', 'Tan'] and nTracesPerOption is 2 (e.g. for sin and sin - 1).

然后在您提供的 MWE 中,您将更新 buttons 字段 updatemenus 变量到 makePlotButtons(options, 2)

这篇关于Plotly:如何在下拉菜单中给出不同的标签名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 18:29