Henri
Henri

Reputation: 1235

Customise my own colour palette and use in geopandas map

I want to define a colour palette to use in a geopandas map. I want to fade between two colors, RGB 0-0-90 and RGB 126-193-61.

I've checked out this page: https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html but I don't understand how I can use customized colours based on that information.

fig, ax = plt.subplots(1, figsize=(10, 16))
matplotlib.rcParams["figure.dpi"] = 100
ax.axis('off')
ax.set_title('TITLE', fontdict={'fontsize': '16', 'fontweight' : '3'})
ax.annotate('Källa: Datalagret', xy=(0.7, .05), xycoords='figure fraction', fontsize=11, color='#555555')

sm = plt.cm.ScalarMappable(cmap='GnBu', norm=plt.Normalize(vmin=vmin, vmax=vmax))
fig.colorbar(sm, orientation="horizontal", fraction=0.036, pad=0.015, aspect = 30)

geo_df1.plot(edgecolor='black', column=variable, cmap='GnBu', linewidth=0.2, ax=ax) 

# I'm using GnBu right now, wish to change this to a custom palette.

Upvotes: 1

Views: 1163

Answers (1)

swatchai
swatchai

Reputation: 18812

To create a custom colormap from 2 given colors, ListedColormap can be used. Here is an example code.

import matplotlib
import matplotlib.cm as cm
#from matplotlib.colors import Normalize

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

# Required colors: from_RGB(0-0-90) to_RGB(126-193-61)
RGB1 = [0,0,90]      # dark blue
RGB2 = [126,193,61]  # pale green

N = 256 #number of discrete levels
vals = np.ones((N,4))

vals[:, 0] = np.linspace(RGB1[0]/256, RGB2[0]/256, N)
vals[:, 1] = np.linspace(RGB1[1]/256, RGB2[1]/256, N)
vals[:, 2] = np.linspace(RGB1[2]/256, RGB2[2]/256, N)

# finally, create the required colormap that ranges from
# -- dark blue to pale green
my_cmp = ListedColormap(vals)

# test plot using random data
fig, ax = plt.subplots(figsize=(4, 4))

np.random.seed(1470)
arrdata = 3 + 2.5 * np.random.randn(20, 20)

minv = np.min(arrdata)
maxv = np.max(arrdata)

psm = ax.pcolormesh(arrdata, cmap=my_cmp, rasterized=True, vmin=minv, vmax=maxv)
fig.colorbar(psm, ax=ax)
plt.show()

blu2green

Upvotes: 1

Related Questions