【问题标题】:Plotly: select df to show by using drop-down menuPlotly:使用下拉菜单选择要显示的 df
【发布时间】:2021-12-06 00:59:17
【问题描述】:

目前我有一个带有 4 个子图的 Plotly 图,由单个 Pandas 数据框 (df) 生成。

现在我有一本 dfs 字典:dfs = {'Germany':DF, 'France':DF, ...}

是否可以创建一个带有下拉菜单的图,我可以选择国家并使用该国家的 df 相应地生成 4 个子图?实现这一目标的最简单方法是什么?谢谢。

P.S.:我查看了来自 Plotly 的下拉菜单示例,但它们似乎只适用于单个 df。

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:
    • 考虑了两种不同的方法
    • 首先将dfs 构造成与您描述的相似
    import requests
    import io
    import pandas as pd
    import plotly.express as px
    
    # fmt: off
    # case / death data
    dfall = pd.read_csv(io.StringIO(
        requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
    dfall["date"] = pd.to_datetime(dfall["date"])
    countries = ['Australia', 'Austria', 'France', 'Germany', 'Japan', 'New Zealand', 'Singapore', 'United Kingdom', 'United States']
    # fmt: on
    
    # mimic described dict of dataframes
    dfs = {c: dfall.loc[dfall["location"].eq(c), ["date", "new_cases"]] for c in countries}
    

    方法一 - 将所有数据帧绘制为轨迹

    • 构造dfs中所有数据帧的拼接数据帧
    • updatemenus 是标准跟踪可见性用例
    px.line(
        pd.concat([dfs[c].assign(country=c) for c in dfs.keys()]),
        x="date",
        y="new_cases",
        color="country",
    ).update_traces(visible=False).update_layout(
        updatemenus=[
            {
                "buttons": [
                    {
                        "label": c,
                        "method": "update",
                        "args": [{"visible": [c == c2 for c2 in dfs.keys()]}],
                    }
                    for c in dfs.keys()
                ]
            }
        ]
    )
    

    方法 2 - 更新菜单中的数据

    • 在构造图形时,它必须有一个跟踪,因此使用dfs 中的第一个数据帧
    px.line(dfs[list(dfs.keys())[0]], x="date", y="new_cases").update_layout(
        updatemenus=[
            {
                "buttons": [
                    {
                        "label": c,
                        "method": "restyle",
                        "args": [
                            {"x": [dfs[c]["date"]], "y": [dfs[c]["new_cases"]]},
                        ],
                    }
                    for c in dfs.keys()
                ]
            }
        ]
    )
    
    

    情节表达与子情节

    • 有效地接近一个,每个国家/地区有多个踪迹
    • 如果 countryhovertemplate 中,则建立真值列表
    # mimic describe dict of dataframes
    dfs = {
        c: dfall.loc[
            dfall["location"].eq(c), ["date", "new_cases", "new_deaths", "new_vaccinations"]
        ]
        .set_index("date")
        .stack()
        .reset_index()
        .rename(columns={"level_1": "measure", 0: "value"})
        for c in countries
    }
    
    fig = (
        px.line(
            pd.concat([dfs[c].assign(country=c) for c in dfs.keys()]),
            x="date",
            y="value",
            facet_row="measure",
            color="country",
        )
        .update_layout({f"yaxis{n}": {"matches": None} for n in range(2, 6)})
        .update_traces(visible=False)
    )
    
    fig.update_layout(
        showlegend=False,
        updatemenus=[
            {
                "buttons": [
                    {
                        "label": c,
                        "method": "update",
                        "args": [{"visible": [c in t.hovertemplate for t in fig.data]}],
                    }
                    for c in dfs.keys()
                ]
            }
        ],
        annotations=[
            {**a, **{"text": a["text"].replace("measure=", "")}}
            for a in fig.to_dict()["layout"]["annotations"]
        ],
    )
    

    【讨论】:

    • 感谢您的解决方案!我现在可以使用一个绘图 + 下拉菜单。你知道是否有办法将子图与 Plotly.express 集成?
    • 这是方法1的扩展,已更新答案
    • 非常感谢您,先生!
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多