I want to highlight the edge of grids whose values are valid.
Here's an example. The value of yellow grids is 2 while it's 1 for the purple grids. The purpose is to plot the edges of them in different colors.
import numpy as np
import matplotlib.pyplot as plt
z = np.full([5, 5], np.nan)
# grids with value = 1
z[1, 1] = 1
z[0, 2] = 1
z[1, 3] = 1
# grids with value = 2
z[3, 1] = 2
z[3, 2] = 2
z[3, 3] = 2
plt.pcolormesh(z)
plt.pcolormesh(z, edgecolors='red', facecolors='none')
Goal:
CodePudding user response:
You could loop through Z and draw a rectangle at each of the positions it's not NaN. The rectangles have width and height of 1
; clip_on=False
can be used to avoid that the rectangles are partly clipped away near the plot borders.
import matplotlib.pyplot as plt
import numpy as np
z = np.full([5, 5], np.nan)
# grid cells with value = 1
z[1, 1] = 1
z[0, 2] = 1
z[1, 3] = 1
# grid cells with value = 2
z[3, 1:4] = 2
fig, ax = plt.subplots()
ax.pcolormesh(z, cmap='Pastel1')
for i in range(z.shape[0]):
for j in range(z.shape[1]):
if not np.isnan(z[i, j]):
color = 'dodgerblue' if z[i, j] == 1 else 'crimson'
ax.add_patch(plt.Rectangle((j, i), 1, 1, fc='none', ec=color, lw=3, clip_on=False))
ax.axis('off') # hide axes
plt.show()
For your new question, with irregular boundaries, the code could look like the following. Note that the number of cells in each dimension is one less than the number of boundaries. Also note that the order of the parameters for Rect
are still Rect((x,y),width,height)
and that pcolormesh
still plots the contents of z[i,j]
at the i
'th row and j
'th column. np.meshgrid
takes care of the ordering.
import matplotlib.pyplot as plt
import numpy as np
x1d = np.random.uniform(1, 3, 9).cumsum()
y1d = np.random.uniform(1, 3, 7).cumsum()
x, y = np.meshgrid(x1d, y1d)
z = np.random.randint(0, 3, (x.shape[0] - 1, x.shape[1] - 1)).astype(float)
z[z == 0] = np.nan
fig, ax = plt.subplots()
ax.pcolormesh(x, y, z, cmap='spring')
for i in range(z.shape[0]):
for j in range(z.shape[1]):
if not np.isnan(z[i, j]):
color = 'dodgerblue' if z[i, j] == 1 else 'crimson'
ax.add_patch(
plt.Rectangle((x[i, j], y[i, j]), x[i, j 1] - x[i, j], y[i 1, j] - y[i, j],
fc='none', ec=color, lw=3, clip_on=False))
ax.axis('off') # hide axes
plt.show()