Search code examples
pythonplotlyplotly-pythonplotly-express

How do I apply a color map to a plotly histogram based on a bin's x-values?


I would like to replicate the below matplotlib graph with plotly, but how can I color the histogram bars based on the x values (dates)?

enter image description here


Solution

    • assuming you have a dataframe that has date and count columns
    • have constructed one from a random normal dict for demonstration purposes
    • create an additional column that categories the dates. Have used color
    • then it's simple to use *Plotly Express to generate figure you want
    import numpy as np
    import pandas as pd
    import plotly.express as px
    
    # fmt: off
    df = pd.DataFrame({"date": pd.date_range("23-jan-2022", "1-apr-2027", freq="M")})
    df["count"] = pd.value_counts(pd.cut(np.sort(np.random.normal(0, 0.1, 2000)), bins=len(df)), sort=False).values
    df["color"] = np.select(
        [df["date"].lt("1-jan-24"), df["date"].lt("1-jan-25"), df["date"].lt("1-oct-25")],
        ["blue", "yellow", "orange"],
        "red",
    )
    # fmt: on
    
    px.bar(
        df,
        x="date",
        y="count",
        color="color",
        color_discrete_map={
            "blue": "blue",
            "yellow": "yellow",
            "orange": "orange",
            "red": "red",
        },
    ).update_layout(xaxis={"dtick": "M1"}, showlegend=False)
    

    enter image description here