user_12
user_12

Reputation: 2129

How to change colors based on percentage, US map using plotly choropleth?

I have an example dataset, something like below and I am using this to plot us map, Here's the example

       prob     state_abbr  state_code
0   0.240402    California  CA
1   0.233483    Texas       TX
2   0.130376    New York    NY
3   0.117759    New Jersey  NJ
4   0.115724    Virginia    VA
5   0.081264    Illinois    IL
6   0.080993    Georgia     GA

I have used this code to plot US map and assign these accordingly based on data above and I was succesful and I can also view the plot properly no issues there,

import plotly.express as px

fig = px.choropleth(locations=df["state_code"], locationmode="USA-states", 
                    color=df["prob"], scope="usa", 
                    color_continuous_scale="Viridis")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

US MAP

The changes I need is, in my example dataset, CA has prob of 24% I want it to be very dark, then TX 23% I want it to be less dark compared to previous etc., like that.

Also, if prob == 0%, I want it to be default gray.

And each dark color needs to be a bit different. How can I do it, can someone help out.

Upvotes: 2

Views: 1919

Answers (1)

bas
bas

Reputation: 15462

Look at the documentation on colorscales. There are also many builtin colorscales that I recommend looking at first.

You can also reverse a builtin colorscale:

You can reverse a built-in color scale by appending _r to its name, for color scales given either as a string or a plotly object.

So "Viridis" would become "Viridis_r".

You could also explicitly construct a colorscale:

color_continuous_scale=["red", "green", "blue"]

Or probably the closest to what you described in your question is to do something like this:

color_continuous_scale=[(0, "gray"), (0.1, "yellow"), (1, "purple")]

Which gives us:

custom scale

Adjust the values above according to your requirements.

Upvotes: 2

Related Questions