Skip to content
Advertisement

Multiple hatched areas with different hatch color using pcolor in matplotlib

I’m trying to change the hatch color of a hatched area but nothing seems to be working.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x_range = np.linspace(0, 1, 30)
y_range = np.linspace(0, 1, 30)

Z = np.zeros([30, 30])

Z[:10, :] += -1
Z[-10:, :] += 1

fig, ax = plt.subplots(constrained_layout = True)

cond1 = (Z != -1)
mZ1 = np.ma.array(Z, mask=cond1)
gains_map = ListedColormap(['gainsboro'])
col1 = ax.pcolor(x_range, y_range, mZ1, cmap = gains_map)
hatch1 = ax.pcolor(x_range, y_range, mZ1,
                hatch = '\ \',  zorder = 2, alpha = 0)

cond2 = (Z != 1)
mZ2 = np.ma.array(Z, mask=cond2)
coral_map = ListedColormap(['lightcoral'])
col2 = ax.pcolor(x_range, y_range, mZ2, cmap = coral_map)
hatch2 = ax.pcolor(x_range, y_range, mZ2,
                hatch = '\ \', edgecolor = 'chocolate', zorder = 2, alpha = 0)

In this example I’d like the hatches of the red area to be a color other than black (but not affect the color of the hatches in the gray area). The areas are rectangular here, so other solutions would be possible, but I’d like something that works for more complex areas created by the mask as well. Any help would be appreciated.

Advertisement

Answer

Things to try:

  • use a ListedColormap with 'none' as color to make the facecolor invisible
  • use a linewidth of zero to suppress the lines between the cells
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x_range = np.linspace(0, 1, 31)
y_range = np.linspace(0, 1, 31)

Z = np.zeros([30, 30])

Z[:10, :] += -1
Z[-10:, :] += 1

fig, ax = plt.subplots(constrained_layout=True)

cond1 = (Z != -1)
mZ1 = np.ma.array(Z, mask=cond1)
gains_map = ListedColormap(['gainsboro'])
none_map = ListedColormap(['none'])
col1 = ax.pcolor(x_range, y_range, mZ1, cmap=gains_map)
hatch1 = ax.pcolor(x_range, y_range, mZ1, cmap=none_map,
                   hatch='\ \', edgecolor='red', lw=0, zorder=2)

cond2 = (Z != 1)
mZ2 = np.ma.array(Z, mask=cond2)
coral_map = ListedColormap(['lightcoral'])
col2 = ax.pcolor(x_range, y_range, mZ2, cmap=coral_map)
hatch2 = ax.pcolor(x_range, y_range, mZ2, cmap=none_map,
                   hatch='\ \', edgecolor='green', lw=0, zorder=2)
plt.show()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement