Python 画空间插值图代码

# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import shapefile
from shapely.geometry import Polygon
from shapely.ops import unary_union
import cartopy.io.shapereader as shpreader
import cartopy.crs as ccrs
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
from scipy.interpolate import Rbf


def draw_function(path0, lon, lat, value):
    file = shapefile.Reader(path0)
    rec = file.shapeRecords()
    polygon = list()
    for r in rec:
        polygon.append(Polygon(r.shape.points))
    poly = unary_union(polygon)  # 并集
    ext = list(poly.exterior.coords)  # 外部点
    codes = [Path.MOVETO] + [Path.LINETO] * (len(ext) - 1) + [Path.CLOSEPOLY]
    #    codes += [Path.CLOSEPOLY]
    ext.append(ext[0])  # 起始点
    path = Path(ext, codes)
    patch = PathPatch(path, facecolor='None')

    xi = np.arange(113, 118.5, 0.01)
    yi = np.arange(24, 31, 0.01)
    olon, olat = np.meshgrid(xi, yi)

    # Rbf空间插值
    func = Rbf(lon, lat, value, function='linear')
    oz = func(olon, olat)

    ax = plt.axes(projection=ccrs.PlateCarree())
    box = [113.4, 118.7, 24.1, 30.4]
    ax.set_extent(box, crs=ccrs.PlateCarree())
    ax.add_patch(patch)
    shp = list(shpreader.Reader(path0).geometries())
    pic = plt.contourf(olon, olat, oz)

    for collection in pic.collections:
        collection.set_clip_path(patch)  # 设置显示区域

    # plt.scatter(x, y, marker='.', c='k', s=10)  # 绘制站点

    # # 添加显示站名、数值等标签
    # for i in range(len(z)):
    #     plt.text(x[i], y[i] + 0.05, df['站名'][i], size=5.5, weight=2, wrap=True)
    # # 添加单位标注
    # plt.text(117.75, 27.1, btn_legendunit.get(), size=8, weight=2)
    # 添加地市边界
    ax.add_geometries(shp, ccrs.PlateCarree(), edgecolor='black',
                      facecolor='none', alpha=0.3, linewidth=0.5)  # 加底图

    fig = plt.gcf()
    fig.set_size_inches(4, 4.3)  # 设置图片大小
    plt.axis('off')  # 去除四边框框
    # 图例

    position = fig.add_axes([0.65, 0.15, 0.03, 0.3])  # 位置
    plt.colorbar(pic, cax=position, orientation='vertical')

    plt.show()


if __name__ == '__main__':
    data = pd.read_csv('data.txt', delimiter='\t', header=None)
    path0 = "dishi.shp"
    draw_function(path0, data.iloc[:, 0], data.iloc[:, 1], data.iloc[:, 2])

你可能感兴趣的:(python,开发语言)