繁体   English   中英

在plotly中添加索引作为下拉菜单

[英]Add index as dropdown menu in plotly

我正在使用以下代码绘制图表:

fig = px.line(df, x='Time', y=['one','two'], color= df.index)
fig['layout']['xaxis']['autorange'] = "reversed"
fig.update_layout(legend_title="Price")
fig.show()

我正在使用的数据框如下:

      Time   one    two
100   9:30   129    243
110  10:30   234    453
120  11:00   155    234

想要添加下拉菜单以从索引中选择并在图表中一次显示一行。 例如,如果我从下拉列表中选择 110,它应该只显示该行的图表。 有没有简单的解决方法。 提前谢谢你。

这是我的解决方案:
为了为下拉菜单设置适当的选项,有一个创建选项列表的功能会很有帮助(如下所示)

# Create proper buttons list
def makeButtonsList(idxs):
    buttons = []
    for i, idx in enumerate(idxs):
        visibleArr = np.full((2*df.index.shape[0],), 
                             False, dtype=bool)       # 2x number of booleans since one/two vals are separate plots
        visibleArr[2*i] = True                        # Set two booleans next to each other (representing one & two) to true
        visibleArr[(2*i)+1] = True
        buttons.append(dict(label=str(idx),
                            method='update',
                            args=[{'visible': list(visibleArr)}]))    # 'Visible' arg determines which plots are shown 
                                                                      # depending on which dropdown is selected 
    return buttons

接下来为数据创建跟踪(使用您的示例数据,我创建了一个条形图,但您可以轻松修改它)

traces = []
for i in range(df.Time.shape[0]):
    rowData = df.iloc[i, :]
    time = rowData.Time
    one = rowData.one
    two = rowData.two
    traces.append(go.Bar(x=[time], y=[one], name='One'))
    traces.append(go.Bar(x=[time], y=[two], name='Two'))

其中df是您正在使用的数据框。

最后把它们放在一起并创建 Plotly 情节!

# Import packages
import pandas as pd
import numpy as np

import plotly.graph_objs as go
import plotly.express as px

# Create proper buttons list
def makeButtonsList(idxs):
    buttons = []
    for i, idx in enumerate(idxs):
        visibleArr = np.full((2*df.index.shape[0],), 
                             False, dtype=bool)       # 2x number of booleans since one/two vals are separate plots
        visibleArr[2*i] = True                        # Set two booleans next to each other (representing one & two) to true
        visibleArr[(2*i)+1] = True
        buttons.append(dict(label=str(idx),
                            method='update',
                            args=[{'visible': list(visibleArr)}]))    # 'Visible' arg determines which plots are shown 
                                                                      # depending on which dropdown is selected 
    return buttons

# Create traces
traces = []
for i in range(df.Time.shape[0]):
    rowData = df.iloc[i, :]
    time = rowData.Time
    one = rowData.one
    two = rowData.two
    traces.append(go.Bar(x=[time], y=[one], name='One'))
    traces.append(go.Bar(x=[time], y=[two], name='Two'))

# Create figure
fig = go.Figure(data=traces)

# Add dropdown options
fig.update_layout(
    updatemenus=[
        dict(
            buttons=makeButtonsList(df.index),
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.55,
            xanchor="left",
            y=1.2,
            yanchor="top"
        ),
    ]
)


# Add annotation for index selected
fig.update_layout(
    annotations=[
        dict(text="Index:", showarrow=False,
        x=0, y=1.15, yref="paper", align="left")
    ],
    xaxis_title = 'Time',
    yaxis_title = 'Value',
)

# Show the plot
fig.show()

这是一个示例图: 情节 1

奖励:如果您认为这种方法很乏味,而滑动条就可以很好地完成这项工作,Plotly 支持条形图的动画。 这是您可以使用的以下代码:

fig = px.bar(df, x='Time', y=['one','two'], animation_frame=df.index)
fig.update_layout(title='Data', barmode='group')
fig.show()

这是结果图: 情节2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM