Skip to content

Instantly share code, notes, and snippets.

@jakebrinkmann
Last active March 29, 2023 14:50
Show Gist options
  • Save jakebrinkmann/7414e8789adbbd60cfb062de0c732a49 to your computer and use it in GitHub Desktop.
Save jakebrinkmann/7414e8789adbbd60cfb062de0c732a49 to your computer and use it in GitHub Desktop.
create a custom disctrete levels python matplotlib colormap with no data
def custom_cmap(colors, padding=1.05):
""" Create a custom colormap from a dictionary
Args:
colors <dict>: Levels to colornames
padding <float>: Offset levels
"""
assert(isinstance(colors, dict))
assert(None in colors)
labels = sorted(colors.keys())
clrs = [colors[l] for l in labels]
levels = sorted([-1000, 0] + map(lambda x: x * padding, filter(None, labels)))
cmap, norm = matplotlib.colors.from_levels_and_colors(levels, clrs)
cmap.set_bad(colors[None], 1.)
return cmap, norm, labels
def custom_cbar(cmap, labels, label='CUSTOMCOLORBAR', orientation="horizontal"):
""" Create a custom discrete colobar
Args:
cmap <matplotlib.cmap>: Colormap being used
labels <list>: Labels to apply to discrete colormap
"""
ncolors = len(labels)
mappable = cm.ScalarMappable(cmap=cmap)
mappable.set_array([])
mappable.set_clim(-0.5, ncolors+0.5)
colorbar = plt.colorbar(mappable, label=label, orientation=orientation)
colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
colorbar.set_ticklabels(labels)
#================================
colors = {
1500: "#87096c",
2000: "#d7191c",
3000: "#e75b3a",
4000: "#f89d59",
5000: "#fdc980",
5500: "#feedaa",
6000: "#ebf6ac",
6500: "#c3e586",
7000: "#96d165",
9999: "#58b353",
None: '#1f78b4'
}
fig, ax = plt.subplots(figsize=(10,10))
masked_array = np.ma.array(MY2DMATRiX, mask=np.isnan(MY2DMATRiX))
cmap, norm, labels = custom_cmap(colors)
ax.pcolorfast(masked_array, cmap=cmap, norm=norm)
custom_cbar(cmap, labels)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment