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

Viewed 298

Inspired by this post

I would like to change the color of the bars, each time a button is clicked. It seems that the color of the bars just can't be updated. Does anyone have a hint on this? (Code below)

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",
)
1 Answers

I added another entry to {"x": [dataset[c]], "nbinsx": bins} so that it looks like: {"x": [dataset[c]], "nbinsx": bins, "marker.color": [marker_colors[i]]} where marker_colors is a list of colors I defined. This forum post was a useful resource.

Full code:

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()

enter image description here

Related