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()
How do I fix this? Thank you
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:
The trick is just these 2 lines:
plt.gca().set_xticks(..., minor='true')
plt.grid(which='minor')
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With