24

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?

Justin Nelligan
  • 455
  • 1
  • 6
  • 12

1 Answers1

39

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.

Simon Gibbons
  • 6,969
  • 1
  • 21
  • 34
  • 1
    That is just plain wonderful, thanks a lot! I also have a more complex case - what if multiple highlighted cells that touch each other, and I want to draw borders around them, but get rid of internal borders within a block of highlighted cells? Maybe I should open a new question for that? – Justin Nelligan Jul 08 '15 at 11:25
  • 1
    Answering to myself, I think I can do it with a Polygon patch, thanks Simon! – Justin Nelligan Jul 08 '15 at 11:41
  • How do you add a patch if your plot of cells isn't in a variable? How do you put a normal matplotlib cell matrix into a variable to achieve this method? – user7778287 Apr 02 '19 at 23:13