I am trying to apply color-mapping to a 2d array using matplotlib library and python 3. For simplicity I made a example code to show my problem:
Example Code:
from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np
#just an example array
sample= np.zeros((20,20),dtype=int)
sample[2,2]=sample[4,4]=2
#color-table and color bounds
cmap = colors.ListedColormap(['black','white','red','green'])
bounds=[-6,0,1,99,105]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots()
ax.imshow(sample,interpolation='nearest', cmap=cmap, norm=norm)
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
ax.set_xlim(0, 20)
ax.set_ylim(20, 0)
ax.set_xticks(np.arange(0,20,1))
ax.set_yticks(np.arange(0,20,1))
plt.show()
With this code, I have a 20 by 20 grid that are white everywhere except for two cells of [2,2]
and [4,4]
that should be red. The problem is that when I show my grid, the cells are off by -0.5 in both directions. What I get with this example code is:
if I shift the grids by -0.5 with:
ax.set_xticks(np.arange(-0.5,20,1))
ax.set_yticks(np.arange(-0.5,20,1))
Then my cells look correct and now the grids are all wrong!
what is wrong with my code? I dont really understand how this can happen ?!!