How to fix lines of axes overlapping imshow plot?

Viewed 41

When plotting matrices using matplotlib's imshow function the lines of the axes can overlap the actual plot, see the following minimal example (matshow is just a simple wrapper around imshow):

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(3,3))
ax.matshow(np.random.random((50, 50)), interpolation="none", cmap="Blues")
plt.savefig("example.png", dpi=300)

matplotlib.axes.Axes.imshow example with 50x50 random data

I would expect every entry of the matrix to be represented by a square, but in the top row it is quite obvious that the axis is hiding a bit of the plot resulting in non-square entries. The same is happening for the last column. Since I want the complete matrix to be seen - every entry with the same importance - is there any way this can be fixed?

1 Answers

To me, this is just a visualisation issue. If I run your code and maximise the window, I do not see the overlapping you are talking about: enter image description here enter image description here

Otherwise, remove the spines but without hiding the ticks:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

enter image description here

EDIT

Reduce the thickness of the borders: [x.set_linewidth(0.3) for x in ax.spines.values()]

The following is the exported image:

enter image description here

With 0.2 the exported image looks like this: enter image description here

Related