Animation with pcolormesh routine in matplotlib, how do I initialize the data?

后端 未结 4 727
傲寒
傲寒 2020-12-01 17:23

I am trying to animate a pcolormesh in matplotlib. I have seen many of the examples using the package animation, most of them using a 1D plot routi

4条回答
  •  温柔的废话
    2020-12-01 17:56

    There is an ugly detail you need to take care when using QuadMesh.set_array(). If you intantiate your QuadMesh with X, Y and C you can update the values C by using set_array(). But set_array does not support the same input as the constructor. Reading the source reveals that you need to pass a 1d-array and what is even more puzzling is that depending on the shading setting you might need to cut of your array C.

    Edit: There is even a very old bug report about the confusing array size for shading='flat'.

    That means:

    Using QuadMesh.set_array() with shading = 'flat'

    'flat' is default value for shading.

    # preperation
    import numpy as np
    import matplotlib.pyplot as plt
    plt.ion()
    y = np.linspace(-10, 10, num=1000)
    x = np.linspace(-10, 10, num=1000)
    X, Y = np.meshgrid(x, y)
    C = np.ones((1000, 1000)) * float('nan')
    
    # intantiate empty plot (values = nan)
    pcmesh = plt.pcolormesh(X, Y, C, vmin=-100, vmax=100, shading='flat')
    
    # generate some new data
    C = X * Y
    
    # necessary for shading='flat'
    C = C[:-1, :-1]
    
    # ravel() converts C to a 1d-array
    pcmesh.set_array(C.ravel())
    
    # redraw to update plot with new data
    plt.draw()
    

    Looks like:

    resulting graphic with shadig=flat

    Note that if you omit C = C[:-1, :-1] your will get this broken graphic:

    broken graphic with shading=flat

    Using QuadMesh.set_array() with shading = 'gouraud'

    # preperation (same as for 'flat')
    import numpy as np
    import matplotlib.pyplot as plt
    plt.ion()
    y = np.linspace(-10, 10, num=1000)
    x = np.linspace(-10, 10, num=1000)
    X, Y = np.meshgrid(x, y)
    C = np.ones((1000, 1000)) * float('nan')
    
    # intantiate empty plot (values = nan)
    pcmesh = plt.pcolormesh(X, Y, C, vmin=-100, vmax=100, shading='gouraud')
    
    # generate some new data
    C = X * Y
    
    # here no cut of of last row/column!
    
    # ravel() converts C to a 1d-array
    pcmesh.set_array(C.ravel())
    
    # redraw to update plot with new data
    plt.draw()
    

    If you cut off the last row/column with shade='gouraud' you will get:

    ValueError: total size of new array must be unchanged
    

提交回复
热议问题