Skip to content Skip to sidebar Skip to footer

Matplotlib: Pcolor() Does Not Plot Last Row And Column?

It seems that PCOLOR is chopping off the last row and column of my data set. Printing the shape of zi below reveals that it is (22,22), as I expect, but an area of 21 squares by 21

Solution 1:

A bit late, but just providing an X and Y arguments whose shape is larger by just 1 (in both directions) will display the entire array.

Something like the example bellow:

import numpy as np
import matplotlib.pyplot as plt

#define the space limits:
horizontal_min  = -2.
horizontal_max  =  2.
horizontal_step =  0.1
vertical_min    = -1.
vertical_max    =  1.
vertical_step   =  0.2

# create the arrays
nx  = (horizontal_max - horizontal_min) / horizontal_step
ny  = ( vertical_max  -  vertical_min ) /  vertical_step
Z   = np.zeros((nx,ny))
Y,X = np.meshgrid(np.arange(vertical_min,
                            vertical_max+vertical_step, # THIS LINE...
                            vertical_step),
                  np.arange(horizontal_min,
                            horizontal_max+horizontal_step, # ...& THIS LINE
                            horizontal_step)
                  )
Y2,X2 = np.meshgrid(np.arange(vertical_min,
                              vertical_max, # THIS LINE...
                              vertical_step),
                    np.arange(horizontal_min,
                              horizontal_max, # ...& THIS LINE
                              horizontal_step)
                    )              

# populate the data array (Z)
i     = 0
if nx > ny:
    while i < ny:
        Z[i,i]      =  i+1
        Z[nx-i-1,i] = -i-1
        i          += 1
else:
    while i < ny:
        Z[i,i]      =  i+1
        Z[i,ny-i-1] = -i-1
        i          += 1


# make the graph
fig,axes     = plt.subplots(2,1)
pc_plot1 = axes[0].pcolor(X, Y, Z)
axes[0].set_title('X.shape == Y.shape != Z.shape')
pc_plot2 = axes[1].pcolor(X2, Y2, Z)
axes[1].set_title('X.shape == Y.shape == Z.shape')
for ax in axes:
    ax.axis('equal')
    ax.set_xlim(horizontal_min, horizontal_max)
    ax.set_ylim(vertical_min, vertical_max)
fig.tight_layout()
fig.show()

enter image description here Notice the lines marked with THIS LINE. What they mean is that:

>>>print X.shape,Y.shape,Z.shape
(41, 11) (41, 11) (40, 10)

(For the given example)

Just a small note, using Y,X = np.meshgrid... replaces having to transpose Z (see official documentation).

Solution 2:

The reason is that pcolor counts points on vertices. There are, in fact, 22 and 10 vertices. Use imshow(...,extent[]) instead.

Post a Comment for "Matplotlib: Pcolor() Does Not Plot Last Row And Column?"