Add custom border to certain cells in a matplotlib

2020-05-19 04:38发布

Right now I`m using Seaborn's clustermap to generate some clustered heatmaps - so far so good.

For a certain use case, I need to draw colored borders around specific cells. Is there a way to do that? Or with pcolormesh in matplotlib, or any other way?

1条回答
淡お忘
2楼-- · 2020-05-19 05:14

You can do this by overplotting a Rectangle patch on the cell that you would want to highlight. Using the example plot from the seaborn docs

import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
g = sns.clustermap(flights)

We can highlight a cell by doing

from matplotlib.patches import Rectangle
ax = g.ax_heatmap

ax.add_patch(Rectangle((3, 4), 1, 1, fill=False, edgecolor='blue', lw=3))
plt.show()

This will produce the plot with a highlighted cell like so:

enter image description here

Note the the indexing of the cells is 0 based with the origin at the bottom left.

查看更多
登录 后发表回答