How to change colors for NA values to gray in a choropleth map?

NA%20values%20are%20in%20black

Here above is an ugly choropleth map I created. I’d like to change the na values, those black chunks into light gray so that it’s not that distinct. I only used the built-in color scale. Any way to revise it a bit based on the auto template?

Hi @LY_Air,

You could use the pandas fillna method (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html) to replace the nan values with zero (or some other appropriate value).

-Jon

Hello, Thank you for your reply! Actually I have considered about this but I suppose a new problem will occur as I might need to change the default color bar manually so as not to show that nan value’s color, which might become troublesome. So I ended up not trying this. Hope there could be a cleaner way of doing this? But I’m so happy to receive your comment!! The first reply to my first question on Plotly!!! I’m indeed a newbie for python and plotly but there’re so many valuable resources! I cannot wait to learn more for visualization.

Hi @LY_Air,

Another option is to drop all of the rows with NA values and then style the missing countries using layout.geo properties. Here’s an example (in this example I’m just keeping the first 50 contries, you would drop your NA rows there instead).

import plotly.plotly as py
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

# Filter NA here
# df = df.dropna()
df = df.iloc[:50]

data = [ dict(
        type = 'choropleth',
        locations = df['CODE'],
        z = df['GDP (BILLIONS)'],
        text = df['COUNTRY'],
        colorscale = 'Viridis',
        autocolorscale = False,
        reversescale = True,
        marker = dict(
            line = dict (
                color = 'rgb(180,180,180)',
                width = 0.5
            ) ),
        colorbar = dict(

            tickprefix = '$',
            title = 'GDP<br>Billions US$'),
      ) ]

layout = dict(
    title = '2014 Global GDP<br>Source:\
            <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
            CIA World Factbook</a>',
    geo = dict(
        landcolor = 'lightgray',
        showland = True,
        showcountries = True,
        countrycolor = 'gray',
        countrywidth = 0.5,
        projection = dict(
            type = 'natural earth'
        )
    )
)

fig = go.FigureWidget( data=data, layout=layout )
fig

Hope that helps,
-Jon

1 Like

Exactly what I want!
That’s pretty cool!
Thank you for your detailed example, I could learn a lot from it!
Happy Thanksgiving holiday!

1 Like