Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib : display array values with imshow

I'm trying to create a grid using a matplotlib function like imshow.
From this array:

[[ 1  8 13 29 17 26 10  4], [16 25 31  5 21 30 19 15]] 

I would like to plot the value as a color AND the text value itself (1,2, ...) on the same grid. This is what I have for the moment (I can only plot the color associated to each value):

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]]) print 'Here is the array' print grid  fig1, (ax1, ax2)= pyplot.subplots(2, sharex = True, sharey = False) ax1.imshow(grid, interpolation ='none', aspect = 'auto') ax2.imshow(grid, interpolation ='bicubic', aspect = 'auto') pyplot.show()    
like image 408
Ludovic Aphtes Avatar asked Nov 20 '15 14:11

Ludovic Aphtes


1 Answers

You want to loop over the values in grid, and use ax.text to add the label to the plot.

Fortunately, for 2D arrays, numpy has ndenumerate, which makes this quite simple:

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') 

enter image description here

like image 137
tmdavison Avatar answered Oct 09 '22 06:10

tmdavison