基于shapefile的光滑等高线图覆盖与掩盖

2024-09-27 00:18:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多边形形状文件(伊利诺伊州)和一个CSV文件(lat,lon,zvalue)。我想画一个平滑的等高线图来表示这些z值。以下是我的代码:

import glob
import fiona
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.mlab import griddata


# Read in the tabulated data
tabfname = glob.glob("Outputs\\*.csv")[0]
df = pd.read_table(tabfname, sep=",")
print(df.head())
lat, lon, z = list(df.y), list(df.x), list(df["Theil Sen Slope"])
z0, z1, z2 = np.min(z)+0.03, np.mean(z), np.max(z)-0.01


# Read some metadata of the shapefile
shp = glob.glob("GIS\\*.shp")[0]
with fiona.drivers():
    with fiona.open(shp) as src:
        bnds = src.bounds        
extent = [values for values in bnds]
lono = np.mean([extent[0], extent[2]])     
lato = np.mean([extent[1], extent[3]])
llcrnrlon = extent[0]-0.5
llcrnrlat = extent[1]-0.5
urcrnrlon = extent[2]+0.5
urcrnrlat = extent[3]+0.5


# Create a Basemap
fig = plt.figure()
ax = fig.add_subplot(111)

m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat,
            urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat,
             resolution='i', projection='tmerc' , lat_0 = lato, lon_0 = lono)
# Read in and display the shapefile
m.readshapefile(shp.split(".")[0], 'shf', zorder=2, drawbounds=True)


# Compute the number of bins to aggregate data
nx = 100
ny = 100

# Create a mesh and interpolate data
xi = np.linspace(llcrnrlon, urcrnrlon, nx)
yi = np.linspace(llcrnrlat, urcrnrlat, ny)
xgrid, ygrid = np.meshgrid(xi, yi)
xs, ys = m(xgrid, ygrid) 
zs = griddata(lon, lat, z, xgrid, ygrid, interp='nn')

# Plot the contour map
conf = m.contourf(xs, ys, zs, 30, zorder=1, cmap='jet')
cbar = m.colorbar(conf, location='bottom', pad="5%", ticks=(z0, z1, z2))

# Scatter plot of the points that make up the contour
for x, y in zip(lon, lat):
    X, Y = m(x,y)
    m.scatter(X, Y, zorder=4, color='black', s=1)

plt.show()
fig.savefig("Myplot.png", format="png")

这是我得到的输出(散布的黑点显示了插值产生的点的空间分布。此处使用最近邻插值法: enter image description here

我基本上参考了以下两个链接中给出的示例来绘制此图:

现在这个图像有3个问题:

  1. 插值轮廓不会在整个shapefile内展开
  2. 轮廓图中突出于shapefile边界的部分不会被遮罩
  3. 轮廓不光滑。在

我想要的是克服这三个缺点,并生成一个平滑和好看的情节,类似于下面所示的(来源:https://doi.org/10.1175/JCLI3557.1): enter image description hereSource:https://doi.org/10.1175/JCLI3557.1

我怎样才能做到呢?在


Tags: theinimportdfasnpextentglob

热门问题