Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a striped patch in matplotlib?

I would like to make a patch (e.g., a Rectangle) that is striped (e.g. alternating yellow and red lines of equal thickness at an angle of 45º). I can think of two ways, but both seem more complicated than they should be: 1) making an implot and masking it, and 2) generating a separate patch for each stripe. Is there a better way to do this, preferably one that can be saved as vector graphic?

like image 549
christianbrodbeck Avatar asked Oct 27 '25 08:10

christianbrodbeck


1 Answers

Depending on what the desired output is, you may use hatching. This has several drawbacks; but may still fulfill the needs.

import matplotlib.pyplot as plt

plt.rcParams["hatch.linewidth"] = 4
rec1 = plt.Rectangle((1,1),2,1.5, facecolor="limegreen", 
                     edgecolor="darkgreen", hatch=r"\\" )

rec2 = plt.Rectangle((4,2),1,1, facecolor="indigo", 
                     edgecolor="gold", hatch=r"//")

fig, ax = plt.subplots()
ax.add_patch(rec1)
ax.add_patch(rec2)
ax.margins(0.3)
ax.autoscale()
plt.show()

enter image description here

As you can see you need to set the hatching linewidth via the rcParams. Also, there is no controll over the angle of hatching, it is 0,45,90 degrees only. Finally, the hatching density will depend on the figure size and dpi used.

like image 131
ImportanceOfBeingErnest Avatar answered Oct 29 '25 21:10

ImportanceOfBeingErnest