Skip to content Skip to sidebar Skip to footer

Adding Hatches To Seaborn Heatmap Plot

Is there a way to hatch particular 'cells' in a seaborn heatmap, which e.g. fullfill a condition? I already tried it with masked arrays and matplotlib pcolor, but it turned out tha

Solution 1:

I think the idea/strategy is correct. You just didn't use the correct coordinates.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
print(flights)
zm = np.ma.masked_less(flights.values, 200)
x= np.arange(len(flights.columns)+1)
y= np.arange(len(flights.index)+1)
sns.heatmap(flights,linewidth=.1)
plt.pcolor(x, y, zm, hatch='//', alpha=0.)

plt.show()

enter image description here

Potentially, one might want to hatch individual cells, instead of the complete area. This is hard. A wordaround is to create a grid of minor ticks and colorize it in white as to overlay the hatching.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

plt.rcParams["axes.axisbelow"] = False

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")

zm = np.ma.masked_less(flights.values, 200)
x= np.arange(len(flights.columns)+1)
y= np.arange(len(flights.index)+1)

fig, ax = plt.subplots()
sns.heatmap(flights,linewidth=0, ax=ax)

ax.pcolor(x, y, zm, hatch='//', alpha=0.)

ax.set_xticks(np.arange(flights.shape[1]+1), minor=True)
ax.set_yticks(np.arange(flights.shape[1]+1), minor=True)
ax.grid(True, which="minor", color="w", linewidth=2)
ax.tick_params(which="minor", left=False, bottom=False)

plt.show()

enter image description here

Post a Comment for "Adding Hatches To Seaborn Heatmap Plot"