order issue of numpy meshgrid

created at 08-05-2021 views: 17

numpy.meshgrid is used when generating (x, y) positions. It was originally written:

xx, yy = np.meshgrid(x, y)

But in actual use, it was found that this would cause the x and y in the image to be reversed, which should be the other way around.

Problem

Since the parameters passed by bar3d need to be serialized into one-dimensional, the position, data, and color need to be traversed in the same order in the matrix, which is reflected in the position (xx, yy), data ( acc), color (color_list) are expanded with ravel() (all should be replaced with flatten()).

However, the position matrix generated by meshgrid will not be in the same order as the data after expansion with ravel().

import numpy as np


z = np.arange(16).reshape(4, 4)
print(z)
x = y = np.arange(4)
xx, yy = np.meshgrid(x, y)  # here
print(xx)
print(yy)

# Contrast: custom traversal order, meshgrid order, reverse-meshgrid order
for i in range(4):
    for j in range(4):
        _i, _j = xx[i][j], yy[i][j]

        print(z[i][j], '\t', z[_i][_j], '\t', z[_j][_i])

# Use `ravel` serialization
xx_flat, yy_flat, z_flat = xx.ravel(), yy.ravel(), z.ravel()
for i in range(16):
    _x, _y = xx_flat[i], yy_flat[i]
   # Habits, meshgrid, anti-meshgrid
    print(z_flat[i], '\t', z[_x][_y], '\t', z[_y][_x])

From the output, it can be seen that the order of the "anti-meshgrid" in the third column is consistent with the custom traversal order, that is, the row main order.

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

[[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]

[[0 0 0 0]
 [1 1 1 1]
 [2 2 2 2]
 [3 3 3 3]]

0        0       0
1        4       1
2        8       2
3        12      3
4        1       4
5        5       5
6        9       6
7        13      7
8        2       8
9        6       9
10       10      10
11       14      11
12       3       12
13       7       13
14       11      14
15       15      15

0        0       0
1        4       1
2        8       2
3        12      3
4        1       4
5        5       5
6        9       6
7        13      7
8        2       8
9        6       9
10       10      10
11       14      11
12       3       12
13       7       13
14       11      14
15       15      15

summary

When using meshgrid, reverse x and y, that is, xx, yy = np.meshgrid(y, x) or yy, xx = np.meshgrid(x, y).

created at:08-05-2021
edited at: 08-05-2021: