如何使用 plotly (python) 中的按钮更改直方图颜色?

How to change histogram color with buttons in plotly (python)?

我想在每次单击按钮时更改条形的颜色。似乎条形的颜色无法更新。有人对此有提示吗? (下面的代码)

dataset = pd.DataFrame(
    {
        "age": [19, 18, 28, 33, 32],
        "bmi": [27.9, 33.77, 33.0, 22.705, 28.88],
        "children": [0, 1, 3, 0, 0],
    }
)
col_bins = {c: int(dataset[c].max() - dataset[c].min()) for c in dataset.columns}

fig = px.histogram(
    x=dataset["age"], nbins=col_bins["age"], color_discrete_sequence=["darkred"]
)
fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": c,
                    "method": "update",
                    "args": [{"x": [dataset[c]], "nbinsx": bins}, {"xaxis.title": c}],
                }
                for c, bins in col_bins.items()
            ],
            "direction": "right",
            "type": "buttons",
            "x": 1,
            "y": 1.15,
        }
    ],
    xaxis_title="age",
    title_text="Histograms",
)

我在 {"x": [dataset[c]], "nbinsx": bins} 中添加了另一个条目,它看起来像:{"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]} 其中 marker_colors 是我定义的颜色列表。 forum post 是有用的资源。

完整代码:

import pandas as pd
import plotly.express as px

dataset = pd.DataFrame(
    {
        "age": [19, 18, 28, 33, 32],
        "bmi": [27.9, 33.77, 33.0, 22.705, 28.88],
        "children": [0, 1, 3, 0, 0],
    }
)

col_bins = {c: int(dataset[c].max() - dataset[c].min()) for c in dataset.columns}

marker_colors = ['#1f77b4','#ff7f0e','#2ca02c']

fig = px.histogram(
    x=dataset["age"], nbins=col_bins["age"]
)
fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": c,
                    "method": "update",
                    "args": [
                        {"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]},
                        {'xaxis.title': c},
                    ],
                }
                for i, (c, bins) in enumerate(col_bins.items())
            ],
            "direction": "right",
            "type": "buttons",
            "x": 1,
            "y": 1.15,
        }
    ],
    xaxis_title="age",
    title_text="Histograms",
)

fig.show()