Last active
September 15, 2021 23:55
-
-
Save bdjackson/2215109d2eaa8c68919c to your computer and use it in GitHub Desktop.
Setting the midpoint of a matplotlib colormap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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