Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: stackplot with different hatches

I want to create a stackplot using python matplotlib library, which I did as on the below pseudocode

plt.stackplot(x,
          [first_value, second_value, third_value], 
          colors=['color1','color2','color3'])

However I want to add to each part (i.e., first_value, second_value, third_value) different hatches, but the hatch command works on the whole plot. How can I pass to the stackplot a list of different hatches?

like image 791
Ziva Avatar asked Feb 03 '26 15:02

Ziva


1 Answers

The stackplot does not have an argument to set the hatching individually on the different polygons. So the idea would be to loop over the different stacks and set a respective hatching.

stackplot returns a list of all the stacks we can use for that purpose.

import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt

fnx = lambda x: np.random.randint(5, 50, 10)
y = np.row_stack((fnx(0), fnx(0), fnx(0)))
x = np.arange(10)

fig, ax = plt.subplots()
stacks = ax.stackplot(x, y)

hatches=["\\", "//","+"]
for stack, hatch in zip(stacks, hatches):
    stack.set_hatch(hatch)

plt.show()

enter image description here

like image 134
ImportanceOfBeingErnest Avatar answered Feb 05 '26 06:02

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!