Matplotlib: `pcolormesh.get_array()` returns flattened array - how to get 2D data back?

后端 未结 2 1221
面向向阳花
面向向阳花 2021-01-06 11:56

I\'m trying to get the data values along a line (like in this hint). That example uses imshow(), but I\'m currently using pcolormesh() to plot.

2条回答
  •  难免孤独
    2021-01-06 12:03

    The shape of the array in stored in private attributes, _meshWidth and _meshHeight. Nevertheless, since these attributes are not part of the public API, it would be better to save the shape of the original data than to rely on these if possible.

    import matplotlib.pyplot as plt
    import numpy as np
    
    D = np.random.uniform(0, 100, size=(5, 5))
    fig, ax = plt.subplots()
    h, w = D.shape
    img = ax.pcolormesh( np.arange(h+1), np.arange(w+1), D)
    
    D2 = img.get_array().reshape(img._meshWidth, img._meshHeight)
    assert  np.array_equal(D, D2)
    

    Note also that if you wish to recover the original array D, then the coordinate arrays, np.arange(h+1), np.arange(w+1) must have lengths one bigger than the shape of D. Otherwise, img.get_array() returns an array of shape (499, 499) when D has shape (500, 500).

提交回复
热议问题