Make contour of scatter

前端 未结 3 2232
北恋
北恋 2020-11-22 13:40

In python, If I have a set of data

x, y, z

I can make a scatter with

import matplotlib.pyplot as plt
plt.scatter(x,y,c=z)
         


        
3条回答
  •  感动是毒
    2020-11-22 13:55

    The solution will depend on how the data is organized.

    Data on regular grid

    If the x and y data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.

    #x  y  z
     4  1  3
     6  1  8
     8  1 -9
     4  2 10
     6  2 -1
     8  2 -8
     4  3  8
     6  3 -9
     8  3  0
     4  4 -1
     6  4 -8
     8  4  8 
    

    can plotted as a contour using

    import matplotlib.pyplot as plt
    import numpy as np
    x,y,z = np.loadtxt("data.txt", unpack=True)
    plt.contour(x.reshape(4,3), y.reshape(4,3), z.reshape(4,3))
    

    Arbitrary data

    a. Interpolation

    In case the data is not living on a quadrilateral grid, one can interpolate the data on a grid. One way to do so is scipy.interpolate.griddata

    import numpy as np
    from scipy.interpolate import griddata
    
    xi = np.linspace(4, 8, 10)
    yi = np.linspace(1, 4, 10)
    zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')
    plt.contour(xi, yi, zi)
    

    b. Non-gridded contour

    Finally, one can plot a contour completely without the use of a quadrilateral grid. This can be done using tricontour.

    plt.tricontour(x,y,z)
    

    An example comparing the latter two methods is found on the matplotlib page.

提交回复
热议问题