Windstorm1981
Windstorm1981

Reputation: 2680

Continuous Color Map on Cartopy

I'm having some difficulty applying a matplotlib continuous color map to values and plotting them correctly in Cartopy.

I have some values that correspond to states in a dataframe and I want to use a two-color continuous scale like RdBu. The colors should be centered around 0 (positive numbers one color with increasingly intense shade, negative numbers another color with increasing intensity the more negative they get). I'm not sure how to normalize the values and add to the the ax.

Key elements of code are below:

import cartopy.crs as ccrs
from cartopy.io import shapereader
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

series = pd.Series([0.05,0.07,-0.02,-0.01], 
                   index=['Arkansas','Alabama','Texas','Illinois'])


df = pd.DataFrame([series], columns=['values'])

#Note:  Assume dataframe has index/values for all states

shapes = ne_110m_admin_1_states_provinces.shp'
reader = shapereader.Reader(shapes)
shapes = list(reader.geometries())
states = reader.records()


fig, ax = plt.subplots(figsize=(20, 15))
projection = ccrs.AlbersEqualArea(central_longitude=-100)
ax1 = fig.add_axes([-.05, -.05, 1.2, 1.2], projection=projection)
ax1.set_extent([-125, -66.5, 20, 50])

cmap = mpl.cm.RdBu

for i, state in enumerate(states):

    ax1.add_geometries(shapes[i], ccrs.PlateCarree(),
                       edgecolor='black',
                       facecolor=cmap(df.loc[state.attributes['name'], 'value']),
                       alpha=0.5, )

plt.show()

I'm not sure how to invoke normalization on my dataset so I have a continuous range between my min and max dataframe values and get the states to color appropriately.

Any help appreciated.

Upvotes: 0

Views: 1299

Answers (1)

DopplerShift
DopplerShift

Reputation: 5853

plt.Normalize creates an object that handles mapping your data to the range [0, 1], which is what the colormap is looking for, so you use this instance instance on your data before passing to cmap. Like:

norm = plt.Normalize(min_val, max_val)
color = cmap(norm(df.loc[state.attributes['name'], 'value']))

Assuming your pandas invocation is correct.

Upvotes: 1

Related Questions