Make contour of scatter

前端 未结 3 2197
北恋
北恋 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 14:03

    contour expects regularly gridded data. You thus need to interpolate your data first:

    import numpy as np
    from scipy.interpolate import griddata
    import matplotlib.pyplot as plt
    import numpy.ma as ma
    from numpy.random import uniform, seed
    # make up some randomly distributed data
    seed(1234)
    npts = 200
    x = uniform(-2,2,npts)
    y = uniform(-2,2,npts)
    z = x*np.exp(-x**2-y**2)
    # define grid.
    xi = np.linspace(-2.1,2.1,100)
    yi = np.linspace(-2.1,2.1,100)
    # grid the data.
    zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
    # contour the gridded data, plotting dots at the randomly spaced data points.
    CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
    CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
    plt.colorbar() # draw colorbar
    # plot data points.
    plt.scatter(x,y,marker='o',c='b',s=5)
    plt.xlim(-2,2)
    plt.ylim(-2,2)
    plt.title('griddata test (%d points)' % npts)
    plt.show()
    

    Note that I shamelessly stole this code from the excellent matplotlib cookbook

提交回复
热议问题