Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib's matshow not aligned with grid

I have a 6x6 matrix that represents a grid. On part of that grid I have a smaller grid (3x3) represented below:

In [65]:

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1
arr
Out[65]:
array([[ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

I wish to plot this, but matplotlib misalignes it, as you can see below. The red square is supposed to cover the area from 0 to 3 on both the horizontal and vertical axis.

In [88]:

plt.matshow(arr)
plt.grid()

enter image description here

How do I fix this? Thank you

like image 287
luffe Avatar asked Mar 05 '15 18:03

luffe


2 Answers

You could use major ticks for labels and minor ticks for the grid.

Consider:

import matplotlib.pyplot as plt
import numpy as np

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1

plt.matshow(arr)

# This is very hack-ish
plt.gca().set_xticks([x - 0.5 for x in plt.gca().get_xticks()][1:], minor='true')
plt.gca().set_yticks([y - 0.5 for y in plt.gca().get_yticks()][1:], minor='true')
plt.grid(which='minor')

plt.show()

Which shows:

Output

The trick is just these 2 lines:

plt.gca().set_xticks(..., minor='true')
plt.grid(which='minor')
like image 132
jedwards Avatar answered Nov 05 '22 12:11

jedwards


If you wish, you can use:

matshow(arr, extent=[0, 6, 0, 6])

However, the standard behaviour is as expected: the pixel centred at (0, 0) has the value of element (0, 0).

like image 4
mdurant Avatar answered Nov 05 '22 13:11

mdurant