FaCoffee
FaCoffee

Reputation: 7909

Matplotlib: display element indices in imshow

From this answer I know how to plot an image showing the array values. But how to show the i,j indices of each element of the array, instead of the values themselves?

This is how the values are printed in the image:

from matplotlib import pyplot
import numpy as np

grid = np.array([[1,8,13,29,17,26,10,4],[16,25,31,5,21,30,19,15]])

fig1, (ax1, ax2)= pyplot.subplots(2, sharex = True, sharey = False)
ax1.imshow(grid, interpolation ='none', aspect = 'auto')
ax2.imshow(grid, interpolation ='bicubic', aspect = 'auto')
for (j,i),label in np.ndenumerate(grid):
    ax1.text(i,j,label,ha='center',va='center')
    ax2.text(i,j,label,ha='center',va='center')
pyplot.show() 

enter image description here

Now, how do you make imshow plot (0,0) in the upper left corner instead of the value 1? What do you change in

for (j,i),label in np.ndenumerate(grid):
        ax1.text(i,j,label,ha='center',va='center')
        ax2.text(i,j,label,ha='center',va='center')

Upvotes: 1

Views: 3487

Answers (1)

MB-F
MB-F

Reputation: 23637

Build a string-valued label from the coordinates i and j, like this:

from matplotlib import pyplot
import numpy as np

grid = np.array([[1,8,13,29,17,26,10,4],[16,25,31,5,21,30,19,15]])

fig1, (ax1, ax2)= pyplot.subplots(2, sharex = True, sharey = False)
ax1.imshow(grid, interpolation ='none', aspect = 'auto')
ax2.imshow(grid, interpolation ='bicubic', aspect = 'auto')
for (j, i), _ in np.ndenumerate(grid):
    label = '({},{})'.format(j, i)
    ax1.text(i,j,label,ha='center',va='center')
    ax2.text(i,j,label,ha='center',va='center')
pyplot.show() 

enter image description here

Upvotes: 2

Related Questions