Home > Net >  Plot Array as Grid with values in Python
Plot Array as Grid with values in Python

Time:10-25

I need to plot an array. I tried the code from Joe Kington (Show the values in the grid using matplotlib), but I get the error: 'for (i, j), z in np.ndenumerate(array): ValueError: too many values to unpack (expected 2)'. Can someone please help me find the mistake? This is the array:

[[[0.953 0.938 0.938]
[0.959 0.951 0.944]
[0.977 0.976 0.973]]]

and this is the code I tried:

with rasterio.open("C:/Users/...raster.tif") as data:
    array = data.read()
  
    fig, ax = plt.subplots()
    ax.matshow(array, cmap='Greens')
    ax.axis('off')
    for (i, j), z in np.ndenumerate(array):
        ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

    fig = plt.gcf()
    plt.savefig("C:/Users/...grid.jpeg")
    plt.close(fig)

CodePudding user response:

Try something like this:

import matplotlib.pyplot as plt

array = np.array([[[0.953, 0.938, 0.938],
[0.959, 0.951, 0.944],
[0.977, 0.976, 0.973]]])

fig, ax = plt.subplots()
ax.matshow(array, cmap='Greens')
ax.axis('off')
for (i, j), z in np.ndenumerate(array[0]):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

fig = plt.gcf()

or squeeze the first dimension of your array: array = array.squeeze(axis=0), before using it in your for loop.

CodePudding user response:

As you can see in the linked question Show the values in the grid using matplotlib it has given a 2D array as grid input (2 brackets at begin and end):

data = [['basis', 2007, 2008],
        [1, 2.2, 3.4],
        [2, 0, -2.2],
        [3, -4.1, -2.5],
        [4, -5.8, 1.2],
        [5, -5.4, -3.6],
        [6, 1.4, -5.9]]

Yours is 3-dimensional (3 brackets at begin and end) and syntactical malformed, without commas separating each element:

[[[0.953 0.938 0.938]
[0.959 0.951 0.944]
[0.977 0.976 0.973]]]

Maybe you can adjust your input right away or transform it as suggested by Alone Together using NumPy's squeeze.

  • Related