Skip to content

Instantly share code, notes, and snippets.

@mseri
Created March 1, 2022 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mseri/433f66c680705461cee1efb2cbd7d1ef to your computer and use it in GitHub Desktop.
Save mseri/433f66c680705461cee1efb2cbd7d1ef to your computer and use it in GitHub Desktop.
Hatched contourf plots in matplolib
# From https://github.com/matplotlib/matplotlib/issues/2789/#issuecomment-604599060
# Content as in example
# ------------------------------
import matplotlib.pyplot as plt
import numpy as np
# invent some numbers, turning the x and y arrays into simple
# 2d arrays, which make combining them together easier.
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)
# we no longer need x and y to be 2 dimensional, so flatten them.
x, y = x.flatten(), y.flatten()
# a plot of hatches without color with a legend
plt.figure()
n_levels = 6
plt.contour(x, y, z, n_levels, colors='black', linestyles='-')
cs = plt.contourf(
x, y, z, n_levels, colors='none',
hatches=['.', '/', '\\', None, '\\\\', '*'],
extend='lower',
)
plt.title('Before')
plt.savefig("mpl_test_before.jpeg")
# ------------------------------
# New bit here that handles changing the color of hatches
colors = ['maroon', 'red', 'darkorange', 'gold', 'forestgreen',
'darkturquoise', 'dodgerblue', 'darkviolet']
# For each level, we set the color of its hatch
for i, collection in enumerate(cs.collections):
collection.set_edgecolor(colors[i % len(colors)])
# Doing this also colors in the box around each level
# We can remove the colored line around the levels by setting the linewidth to 0
for collection in cs.collections:
collection.set_linewidth(0.)
# ------------------------------
plt.title('After')
plt.savefig("mpl_test_after.jpeg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment