Skip to content

Instantly share code, notes, and snippets.

@j08lue
Created April 15, 2013 15:05
Show Gist options
  • Save j08lue/5388773 to your computer and use it in GitHub Desktop.
Save j08lue/5388773 to your computer and use it in GitHub Desktop.
Convert matplotlib contours to hatched patches
"""Convert matplotlib contours to hatched patches"""
from matplotlib.patches import PathPatch
from itertools import cycle
def contour_to_hatched_patches(cntrset, hatch_colors, hatch_patterns,
remove_contour=True):
"""Convert matplotlib contours to hatched patches"""
patches_list = []
for pathcollection in cntrset.collections:
patches_list.append([PathPatch(p1) for p1 in pathcollection.get_paths()])
if remove_contour:
pathcollection.remove()
for patches, hc, hp in zip(patches_list,
cycle(hatch_colors), cycle(hatch_patterns)):
for p in patches:
p.set_fc("none")
p.set_ec("k")
p.set_hatch(hp)
ax.add_patch(p)
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
y, x = np.indices((10,10))
dx, dy = x - 4.5, y-4.5
dr2 = dx*dx+dy*dy
arr = np.exp(-dr2/16.)
plt.figure()
ax = plt.subplot(111)
cntrset = ax.contourf(dx,dy,arr)
hatch_colors = "k"
hatch_patterns = "/\|-+xoO.*"
contour_to_hatched_patches(cntrset, hatch_colors, hatch_patterns,
remove_contour=True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment