Mikful
Mikful

Reputation: 23

Add borders to grid plot based on value

I wonder if you can help me with this. I have a grid of 0's and 1's that I want to add a border colour to the plot cell area if it's a 1. I've used imshow to produce a grid coloured according to value, e.g.:

a = np.random.randint(2, size=(10,10))

im = plt.imshow(a, cmap='Blues', interpolation='none', vmin=0, vmax=1, aspect='equal')

Grid

However, I can't find any border properties to change for each grid cell in imshow. I've read add_patch could be used to place a rectangle at certain points to mimic a border using on the axes values, but is there a better way than looping and applying cell-wise?

Upvotes: 2

Views: 2942

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339210

There is no build-in function to partially colorize imshow edges. The easiest option is probably indeed to draw a rectangle for each cell.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.randint(2, size=(10,10))

im = plt.imshow(a, cmap='Blues', interpolation='none', vmin=0, vmax=1, aspect='equal')

def rect(pos):
    r = plt.Rectangle(pos-0.5, 1,1, facecolor="none", edgecolor="k", linewidth=2)
    plt.gca().add_patch(r)

x,y = np.meshgrid(np.arange(a.shape[1]),np.arange(a.shape[0]))
m = np.c_[x[a.astype(bool)],y[a.astype(bool)]]
for pos in m:
    rect(pos)

plt.show()

enter image description here

Upvotes: 5

Related Questions