Search code examples
plotlyhistogram

Plotly histogram continuous colors based on "count of" column?


I have created a histogram that shows the amount of days hotter than 35° celsius per decade ("Jahrzehnt" in German). I would like to color it based on the amount of hot days (here the "Temperatur, Maximum" column), however as you can see in the picture, the hottest decade (2010) got the fainted color although I want it to be dark red.

enter image description here

my code is

    fig = px.histogram(grouper, x='Jahrzehnt', y='Temperatur, Maximum', color='Temperatur, Maximum', \
        color_discrete_sequence=px.colors.sequential.Reds,
        title='Tage über 35° Celsius ("Wüstentage")',
        hover_data=dict(Jahrzehnt=False)
        )
    fig.update_layout(showlegend=False)
    fig.update_yaxes(title='Anzahl')

How can change the color_discrete_sequence to make it match lowest and highest values with fainted to satured reds?

Thank you for any hints.


Solution

  • import pandas as pd
    import numpy as np
    import plotly.express as px
    
    grouper = pd.DataFrame(
        {
            "Jahrzehnt": range(1870, 2011, 10),
            "Temperatur, Maximum": np.random.randint(2, 40, 15),
        }
    )
    grouper["Jahrzehnt"] = grouper["Jahrzehnt"].astype(str) + "er"
    
    fig = px.histogram(
        grouper,
        x="Jahrzehnt",
        y="Temperatur, Maximum",
        color="Jahrzehnt",
        color_discrete_sequence=[
            px.colors.sample_colorscale("reds", v)[0]
            for v in (
                grouper["Temperatur, Maximum"] / grouper["Temperatur, Maximum"].max()
            ).tolist()
        ],
        title='Tage über 35° Celsius ("Wüstentage")',
        hover_data=dict(Jahrzehnt=False),
    )
    fig.update_layout(showlegend=False)
    fig.update_yaxes(title="Anzahl")
    

    enter image description here