2

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: enter image description here

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! enter image description here

what is wrong with my code? I dont really understand how this can happen ?!!

Hirad Gorgoroth
  • 389
  • 2
  • 4
  • 13

1 Answers1

3

The Notes section of the docstring of ax.imshow says:

Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).

So your call becomes:

ax.imshow(sample, interpolation='none', cmap=cmap, norm=norm,
          extent=[0, 20, 20, 0])
Paul H
  • 65,268
  • 20
  • 159
  • 136