Skip to content

Instantly share code, notes, and snippets.

@willprice
Created October 9, 2019 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willprice/36ddf93f0bdeacb026b18cf6fac2b02a to your computer and use it in GitHub Desktop.
Save willprice/36ddf93f0bdeacb026b18cf6fac2b02a to your computer and use it in GitHub Desktop.
Matplotlib snippet for visualising matrices nicely.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='paper', style='whitegrid')
def grid_show(grid, horizontal_labels, vertical_labels=None, cmap='binary', grid_color='#efefef'):
ax = plt.gca()
image = ax.imshow(grid,
interpolation=None,
extent=(-0.5, grid.shape[1] - 0.5,
-0.5, grid.shape[0] - 0.5),
cmap=cmap)
tick_marks = np.arange(len(grid))
plt.grid(True)
plt.yticks(tick_marks, horizontal_labels[::-1])
plt.xticks(tick_marks, vertical_labels, rotation=90)
if vertical_labels is None:
ax.set_xticklabels([])
plt.setp(ax.spines.values(), linewidth=2)
ax.set_xticks(np.arange(-.5, grid.shape[1] + .5, 1), minor=True)
ax.set_yticks(np.arange(-.5, grid.shape[0] + .5, 1), minor=True)
ax.grid(which='minor', color=grid_color, linestyle='-', linewidth=str(1))
ax.grid(False, which='major')
ax.set(frame_on=True)
ax.tick_params(axis='both', which='both', length=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment