How to visualize scalar 2D data with Matplotlib?

前端 未结 4 991
梦谈多话
梦谈多话 2021-02-08 10:17

So i have a meshgrid (matrices X and Y) together with scalar data (matrix Z), and i need to visualize this. Preferably some 2D image with colors at the points showing the value

4条回答
  •  温柔的废话
    2021-02-08 10:42

    This looks nice, but it's inefficient:

    from pylab import *
    origin = 'lower'
    
    delta = 0.025
    
    x = y = arange(-3.0, 3.01, delta)
    X, Y = meshgrid(x, y)
    Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = 10 * (Z1 - Z2)
    
    nr, nc = Z.shape
    
    CS = contourf(
        X, Y, Z,
        levels = linspace(Z.min(), Z.max(), len(x)),
        ls = '-',
        cmap=cm.bone,
        origin=origin)
    
    CS1 = contour(
        CS,
        levels = linspace(Z.min(), Z.max(), len(x)),
        ls = '-',
        cmap=cm.bone,
        origin=origin)
    
    show()
    

    It it were me, I'd re-interpolate (using scipy.interpolate) the data to a regular grid and use imshow(), setting the extents to fix the axes.

    fine contour

    Edit (per comment):

    Animating a contour plot can be accomplished like this, but, like I said, the above is inefficient just plain abuse of the contour plot function. The most efficient way to do what you want is to employ SciPy. Do you have that installed?

    import matplotlib
    matplotlib.use('TkAgg') # do this before importing pylab
    import time
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    def animate():
        origin = 'lower'
        delta = 0.025
    
        x = y = arange(-3.0, 3.01, delta)
        X, Y = meshgrid(x, y)
        Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
        Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
        Z = 10 * (Z1 - Z2)
    
        CS1 = ax.contourf(
            X, Y, Z,
            levels = linspace(Z.min(), Z.max(), 10),
            cmap=cm.bone,
            origin=origin)
    
        for i in range(10):
            tempCS1 = contourf(
                X, Y, Z,
                levels = linspace(Z.min(), Z.max(), 10),
                cmap=cm.bone,
                origin=origin)
            del tempCS1
            fig.canvas.draw()
            time.sleep(0.1)
            Z += x/10
    
    win = fig.canvas.manager.window
    fig.canvas.manager.window.after(100, animate)
    plt.show()
    

提交回复
热议问题