Skip to content

Instantly share code, notes, and snippets.

@DanielKotik
Forked from bdjackson/SetMidpoint.py
Created April 19, 2018 11:01
Show Gist options
  • Save DanielKotik/cf5cfbbf748f61019584b6942e091d06 to your computer and use it in GitHub Desktop.
Save DanielKotik/cf5cfbbf748f61019584b6942e091d06 to your computer and use it in GitHub Desktop.
Setting the midpoint of a matplotlib colormap
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
class MidpointNormalize(mpl.colors.Normalize):
"""
class to help renormalize the color scale
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mpl.colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# generate data for test plots
x_values = np.random.normal( 0, 1, 10000)
y_values = np.random.normal( 0, 1, 10000)
# plot with default midpoint
fig, ax = plt.subplots()
default_norm = ax.hexbin(x_values, y_values,
cmap=plt.cm.seismic)
default_norm = ax.hexbin(x_values, y_values,
cmap=plt.cm.seismic,
gridsize = (25,25))
fig.colorbar(default_norm)
plt.savefig('default_norm.png')
plt.close()
# plot with custom midpoint
fig, ax = plt.subplots()
norm = MidpointNormalize(midpoint = 20)
my_norm = ax.hexbin(x_values, y_values,
cmap=plt.cm.seismic,
norm = norm,
gridsize = (25,25))
fig.colorbar(my_norm)
plt.savefig('my_norm.png')
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment