Contours with map overlay on irregular grid in python

后端 未结 1 616
囚心锁ツ
囚心锁ツ 2020-12-11 04:01

Here is my data:

Lon   Lat     Z   Z2  pos
32.6  -13.6   41   9  CHIP
27.1  -16.9   43  12  CHOM
32.7  -10.2   46  14  ISOK
24.2  -13.6   33  13  KABO
28.5           


        
相关标签:
1条回答
  • 2020-12-11 04:26

    To start with, let's ignore the map-based part of things, and just treat your lat, long coordinates as a cartesian coordinate system.

    import numpy as np
    import pandas as pd
    from matplotlib.mlab import griddata
    import matplotlib.pyplot as plt
    
    #-- Read the data.
    # I'm going to use `pandas` to read in and work with your data, mostly due to
    # the text site names. Using pandas is optional, however.
    data = pd.read_csv('your_data.txt', delim_whitespace=True)
    
    #-- Now let's grid your data.
    # First we'll make a regular grid to interpolate onto. This is equivalent to
    # your call to `mgrid`, but it's broken down a bit to make it easier to
    # understand. The "30j" in mgrid refers to 30 rows or columns.
    numcols, numrows = 30, 30
    xi = np.linspace(data.Lon.min(), data.Lon.max(), numcols)
    yi = np.linspace(data.Lat.min(), data.Lat.max(), numrows)
    xi, yi = np.meshgrid(xi, yi)
    
    #-- Interpolate at the points in xi, yi
    # "griddata" expects "raw" numpy arrays, so we'll pass in
    # data.x.values instead of just the pandas series data.x
    x, y, z = data.Lon.values, data.Lat.values, data.Z.values
    zi = griddata(x, y, z, xi, yi)
    
    #-- Display the results
    fig, ax = plt.subplots()
    im = ax.contourf(xi, yi, zi)
    ax.scatter(data.Lon, data.Lat, c=data.Z, s=100,
               vmin=zi.min(), vmax=zi.max())
    fig.colorbar(im)
    
    plt.show()
    

    enter image description here

    The "blocky" boundary is due to the coarse (30x30) resolution of the grid. griddata uses a triangulation method, so nothing outside of the convex hull of your data points is interpolated. To see this more clearly, bump up numcols and numrows to, say, 300x300:

    enter image description here

    You could also use several other interpolation methods (particularly if you want to extend the interpolation beyond the convex hull of the data).

    0 讨论(0)
提交回复
热议问题