jackhammer013
jackhammer013

Reputation: 2297

Set specific color for a value in plotly choropleth maps

I have a choropleth map using plotly.express. My map looks like this at the moment:

enter image description here

The highest value is 730 and the lowest value is -11. So the gap between highest and lowest value is huge making the red color expand so much. My question is how do I make the red color only for negative values? I tried to check the

color_discrete_map 

But can't seem to understand how can I implement it in my map. My code currently is like this

colorscale = ["rgb(255, 51, 51)", "rgb(210, 231, 154)", "rgb(94, 179, 39)", "rgb(67, 136, 33)", "rgb(33, 74, 12)"]
fig = px.choropleth(
    df,
    geojson=counties,
    locations="fips",
    color="value",
    color_continuous_scale=colorscale,
    range_color=([min_value, max_value]),
    scope="usa",
    labels={"label": "Name", "value": "Value (%)", "fips": "Geo Id"},
    hover_name="label",
)

My data is from a Dataframe with 3 columns (fips, label, value). I wanted the colors to be red on negative values and a dynamic color of green for non negatives.

Upvotes: 0

Views: 4655

Answers (1)

r-beginners
r-beginners

Reputation: 35115

Edit: Updated graph with intentionally negative data and midpoint set to 0. The color range was also changed to match the data.

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})
# minus data created
df['unemp'] = df['unemp'] - 5

import plotly.express as px

colorscale = ["rgb(255, 51, 51)", "rgb(210, 231, 154)", "rgb(94, 179, 39)", "rgb(67, 136, 33)", "rgb(33, 74, 12)"]

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                    color_continuous_scale=colorscale,
                    color_continuous_midpoint=0,
                    range_color=(-5, 18.5),
                    scope="usa",
                    labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

enter image description here

Upvotes: 1

Related Questions