【问题标题】:How to update data of multiple scatter plots with dropdown buttons in plotly python?python - 如何使用plotly python中的下拉按钮更新多个散点图的数据?
【发布时间】:2021-12-16 02:42:55
【问题描述】:

我在同一轴上有两个变量/数组的两个散点图。我想添加一个下拉列表来更新两个变量/数组的数据。

import numpy as np
import pandas as pd
from plotly import graph_objects as go

scen3_df = pd.DataFrame(np.random.randint(10, 20, (100, 8)), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
orig_df = pd.DataFrame(np.random.randint(0, 10, (100, 8)), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

first_title = scen3_df.columns.to_list()[0]
traces = []
buttons = []
for idx, col in enumerate(scen3_df.columns):

    visible = [False]*8
    visible[idx] = True
    traces.append(go.Scatter(x=scen3_df.index, y=scen3_df[col],
                             name="Scenario 3",
                             visible = True if idx==0 else False,
                             ))

    traces.append(go.Scatter(x=scen3_df.index, y=orig_df[col],
                             name="Original",
                             visible = True if idx==0 else False,
                             ))

    buttons.append(dict(label=col,
                        method="update",
                        args=[{"visible": visible},
                              {"title": f" Gate operation at {col}"}]
                        ))


updatemenus = [{'active':0, "buttons":buttons}]

fig = go.Figure(data=traces,
                 layout=dict(updatemenus=updatemenus))
fig.update_layout(title=first_title, title_x=0.5)
fig.update_yaxes(range=[0, scen3_df.max()], title="Gate Height (m)")
fig.update_xaxes(title="Time (Julian Day)")
fig.show()
fig.write_html("gate_operations.html")

我想要什么

我目前得到的

【问题讨论】:

    标签: python plotly scatter-plot plotly-python


    【解决方案1】:
    • 在构建这些类型的图形和菜单时,一致性始终是关键
    • Plotly Express 实现一致性要简单得多,所以我改用它而不是 图形对象
    • 为两个数据框构建两个图形,然后将它们整合。名称被覆盖以确保图例显示为您想要的
    • 已构建图形,其中包含构建菜单所需的所有信息作为嵌套 list 理解
    import numpy as np
    import pandas as pd
    import plotly.express as px
    
    scen3_df = pd.DataFrame(np.random.randint(10, 20, (100, 8)), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
    orig_df = pd.DataFrame(np.random.randint(0, 10, (100, 8)), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
    
    
    
    # generate equivalent figures for both data frames
    figs = [
        px.line(df, y=df.columns)
        .update_traces(line_color=color, name=name)
        .for_each_trace(lambda t: t.update(visible=t.legendgroup == df.columns[0]))
        for df, color, name in zip(
            [scen3_df, orig_df], ["blue", "red"], ["Scenario 3", "Original"]
        )
    ]
    
    # construct overall figure
    fig = (
        figs[0]
        .add_traces(figs[1].data)
        .update_layout(xaxis_title="Time (Julian Day)", yaxis_title="Gate Height (m)")
    )
    # build the menu
    fig.update_layout(
        updatemenus=[
            {
                "buttons": [
                    {
                        "label": col,
                        "method": "update",
                        "args": [
                            {"visible": [t.legendgroup == col for t in fig.data]},
                            {"title": f" Gate operation at {col}"},
                        ],
                    }
                    for col in scen3_df.columns
                ]
            }
        ]
    )
    

    【讨论】:

    • 感谢您的回答。使用低级图形对象的一个​​原因是我稍后想添加多个下拉菜单,每个下拉菜单都会对正在显示的数据产生影响。这也可以使用 plotly express 吗?
    • 是的 - 查看我提供的代码示例。我正在使用图形对象模型来构建菜单...菜单不是用 px 构建的,而是低级 API。
    猜你喜欢
    • 2018-02-18
    • 2023-04-09
    • 1970-01-01
    • 2020-12-01
    • 2021-10-28
    • 2022-01-16
    • 1970-01-01
    • 2021-10-05
    • 2020-11-07
    相关资源
    最近更新 更多