adding hatches to seaborn heatmap plot

心不动则不痛 提交于 2021-01-29 08:21:22

问题


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 that it hatched the wrong cells.

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

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

plt.show()

回答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()

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()



来源:https://stackoverflow.com/questions/55285013/adding-hatches-to-seaborn-heatmap-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!