How to make values below a certain threshold a certain color?

Hi and happy new year! : )

I have this bit of code, and I would like variables (i.e. countries/Entities) below or at 26 appear in green, while the others are displayed with the ‘normal’ color gradient. How can I do that? I’m beginning in Plotly and any help would be appreciated.

Thanks in advance! : )

My script:

import plotly.express as px
import pandas as pd

df = pd.read_csv('path/to/meat-supply-per-person.csv') fig = px.treemap(df.query('Year==2020 & Code.notna()'), path = [px.Constant('World'), 'Entity'], values = 'Meat – kilograms per year per capita', color = 'Meat – kilograms per year per capita', hover_data = ['Entity', 'Meat – kilograms per year per capita'], title = 'Average Meat Consumption per Capita in 2020')

fig.show()

What the file looks like:

Entity Code Year Meat – kilograms per year per capita
0 Afghanistan AFG 1961 14.719367
1 Afghanistan AFG 1962 14.738824
2 Afghanistan AFG 1963 15.176605
3 Afghanistan AFG 1964 15.378455
4 Afghanistan AFG 1965 15.701337

Hey @MitchBuchanon welcome to the forums!

Yes, thats possible. Here some topics to get you going:

The solutions presented above were not helpful (too convoluted for me as a beginner), but a mix of this and ChatGPT for explanations allowed me to come up with this final script which does what I want with colors:

import pandas as pd
import plotly.express as px

df['Color'] = pd.cut(df['Meat – kilograms per year per capita'], 
    bins=[0, 26, 52, 78, float("inf")],
    labels=['green', 'yellow', 'orange', 'red'],
    include_lowest=True)

fig = px.treemap(df.query('Year==2020 & Code.notna()'), 
    path=['Entity'], 
    values='Meat – kilograms per year per capita', 
    color='Color', 
    color_discrete_map={'green': 'green', 'yellow': 'yellow', 'orange': 'orange','red': 'red'},
    title='Average Meat Consumption per Capita in 2020',
    custom_data = ['Entity', 'Meat – kilograms per year per capita'])

fig.update_traces(
    hovertemplate="<br>".join([
        "%{customdata[0]}",
        "%{customdata[1]}"]))

fig.show()

in case this may help someone at some point… ; )

1 Like