Using set_array with pyplot.pcolormesh ruins

I have an xx and yy matrix created using np.meshgrid and a grid matrix of values โ€‹โ€‹created when working on xx and yy. Then I draw the results using graph = plt.pcolormesh(... and get the following:

enter image description here

Then, when I try to update the grid matrix on the graph using graph.set_array(grid.ravel()) , this leads to the fact that this figure will be disrupted.

enter image description here

Does anyone know how to avoid this?

Here is my complete code if it helps:

 from pylab import * import numpy as np import matplotlib.pyplot as plt from obspy import read dx = 5 # km dt = 5 # sec nx = 500 ny = 500 v = 3.5 # km/s p = 1/v t_min = np.int_(np.sqrt((nx*dx)**2 + (ny*dx)**2))/v nt = np.int_(t_min/dt) # Receiver position rx = 40 * dx ry = 40 * dx # Signal with ones signal = np.zeros(2*nt) signal[0:len(signal):len(signal)/10] = 1 # Create grid: x_vector = np.arange(0, nx)*dx y_vector = np.arange(0, ny)*dx xx, yy = np.meshgrid(x_vector, y_vector) # Distance from source to grid point rr = np.int_(np.sqrt((xx - rx)**2 + (yy - ry)**2)) # travel time grid tt_int = np.int_(rr/v) tt = rr/v # Read window of signal wlen = np.int_(t_min/dt) signal_window = signal[0:wlen] grid = signal_window[tt_int/dt] ax = plt.subplot(111) graph = plt.pcolormesh(xx, yy, grid, cmap=mpl.cm.Reds) plt.colorbar() plt.plot(rx, ry, 'rv', markersize=10) plt.xlabel('km') plt.ylabel('km') # plt.savefig('anitestnormal.png', bbox_inches='tight') signal_window = signal[wlen:wlen * 2] grid = signal_window[tt_int/dt] graph.set_array(grid.ravel()) # plt.ion() plt.show() 
+5
source share
1 answer

It's quite complicated ... but I think your statement about the measurements is correct. This is due to the way pcolormesh creates the QuadMesh object.

The documentation states that:

A quadrangular grid is represented by the formula (2 x ((meshWidth + 1) * (meshHeight + 1))) numpy array

In this context, meshWidth is your xx , meshHeight is your yy . When the kernel defines an array using set_array, pcolormesh wants to interpret it directly as quadrilaterals (meshWidth x meshHeight) and therefore requires less than one in each dimension.

When I tested it, I got the following behavior: if you changed

 graph.set_array(grid.ravel()) 

to

 graph.set_array(grid[:-1,:-1].ravel()) 

your plot will look as it should.

In code, this is similar to the initial call to pcolormesh, if xx and yy , they should be defined as having one more point in each dimension than an array of values, and if they're not (disabled by 1), then the array is automatically trimmed to one value . Thus, you should get the same answer, even if you use grid[:-1,:-1] in the first call.

+4
source

Source: https://habr.com/ru/post/1215221/


All Articles