Basically, what I'm trying to do is the idea explained in the answer for this question.
I plot an image 100 x 100 with imshow and, at certain points, I would like to plot hatches.
So, here is my image example:

This represents the mean of 100 samples of scalar fields. I also have the standard deviation for this samples:

So, what I would like to do is to plot the mean property combined to hatches at the positions in which I have standard deviation > 0.0.
My data are 100 x 100 and its dimension varies form -4 to 4. Following the idea presented here, my current approach was that:
plt.figure()
fig = plt.imshow(scalar_field, origin='lower', extent=(-4, 4, -4, 4))
plt.colorbar(fig)
x_indices = numpy.nonzero(standard_deviation)[0]
y_indices = numpy.nonzero(standard_deviation)[1]
ax = plt.gca()
for p in range(len(x_indices)):
i = x_indices[p]
j = y_indices[p]
ax.add_patch(patches.Rectangle((i-.5, j-.5), 1, 1, hatch='//', fill=False, snap=False))
plt.show()
plt.close()
However, I don't get the patterns at the correct locations. I haven't used patches so far and I don't know if I'm using them in properly way.

Any help would be appreciated.
You need to convert indices (0..99) to the scale of the image (-4..4) and the size of each block is not 1, 1 but 0.08,0.08. Also, you will want ec='None' in the Rectangle to remove the edges between the blocks. I believe it goes:
ax.add_patch(patches.Rectangle(((i-50.5)*0.08-.04, (j-50.5)*0.08), 0.08, 0.08,
hatch='//', fill=False, snap=False, linewidth=0))
However, I suspect that you will fill the whole area with hatching: are you certain that the stddev is in some places exactly zero (it can never be less than zero).
Instead of adding hatches in multiple rectangles, you can add them using contourf as explained in the contourf hatching example. This is a better solution as it is more general and only takes one line:
plt.contourf(mask, 1, hatches=['', '//'], alpha=0)
where mask is a binary image of the same size as your image. Here we set alpha to zero to make the mask itself transparent, and only added hatches to where the mask equals 1. Note also that the origin and extent arguments need to match, so for your code:
plt.contourf(standard_deviation > thresh, 1, hatches=['', '//'], alpha=0,
origin='lower', extent=(-4, 4, -4, 4))
A similar solution is to use pcolor instead of contourf, as explained in this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With