简体   繁体   中英

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

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM