I am looking to create custom hatches that I can use to fill in matplotlib plots. I stumbled across this previous question, which works and creates a single custom hatch. However, when I modify it like in the example code below it plots a blank circle. I am not sure why, but I believe it is linked to adding a new identifier to the available hatch list.
Additionally, I want to be able to supply multiple paths and create new hatchings. How could this be achieved?
Finally, when a new custom hatch is created and added will that always be available in other unrelated scripts or do I need to run the code again in each new script?
import numpy as np
import matplotlib.hatch
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
T_path = Polygon(
[[0.0, -0.2], [0.0, 0.0], [-0.4, 0.0], [0.4, 0.0], [0.0, 0.0], [0.0,
-0.4]],
closed=True, fill=False).get_path()
class TshapeHatch(matplotlib.hatch.Shapes):
"""
Custom hatches defined by a path drawn inside [-0.5, 0.5] square.
Identifier 't'.
"""
filled = False
size = 1.0
path = T_path
def __init__(self, hatch, density):
self.num_rows = (hatch.count('t')) * density
self.shape_vertices = self.path.vertices
self.shape_codes = self.path.codes
matplotlib.hatch.Shapes.__init__(self, hatch, density)
matplotlib.hatch._hatch_types.append(TshapeHatch)
fig = plt.figure()
ax = fig.add_subplot(111)
ellipse = ax.add_patch(Ellipse((0.5, 0.5), 0.3, 0.5, fill=False))
ellipse.set_hatch('t')
ellipse.set_color('red')
plt.show()