pytho地理绘图

本文介绍了如何使用proplot库简化matplotlib绘图的繁琐调整,通过shp2clip函数实现地理区域的矢量裁剪,并展示了如何结合cartopy和shapefile进行京津冀地区数据的高精度地图制作,包括颜色映射和坐标范围设置。
摘要由CSDN通过智能技术生成

前言

  • matplotlib 绘图确实方便,但是具体到每一个细节调整的时候是在太繁琐了,所以我选择了另外一个包:proplot进行后续绘图
pip install proplot

矢量裁剪

  • 这部分代码来源找不到了,记得是气象家园上面的一个帖子
def shp2clip(originfig, ax, shpfile, fieldVals):
    """
    This method enables you to maskout the unneccessary data
                                            outside the interest region
    :param ax:  the Axes instance
    :param shpfile:  the shape file used for clip
    :param fieldVals:  thi features attributes value list in shape file,
                    outside the region the data is to be masked out
    :return:
    """
    sf = shapefile.Reader(shpfile)
    vertices = []
    codes = []
    for shape_rec in sf.shapeRecords():
        if shape_rec.record[0] in fieldVals:  # 注意这里需要指定你的字段的索引号,我的是第3个字段
            pts = shape_rec.shape.points
            prt = list(shape_rec.shape.parts) + [len(pts)]
            for i in range(len(prt) - 1):
                for j in range(prt[i], prt[i + 1]):
                    vertices.append((pts[j][0], pts[j][1]))
                codes += [Path.MOVETO]
                codes += [Path.LINETO] * (prt[i + 1] - prt[i] - 2)
                codes += [Path.CLOSEPOLY]
            clip = Path(vertices, codes)
            clip = PathPatch(clip, transform=ax.transData)

    for contour in originfig.collections:
        contour.set_clip_path(clip)
    return clip

绘图

包的引入

-cmaps需要自行安装,这个包参考的是NCL的配色

import os
import glob
import shapefile
import glob
import gc
import cmaps 
import proplot as plot
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
import cartopy.mpl.ticker as mticker
from osgeo import gdal,osr
import numpy as np
from tqdm import *
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
import cartopy.io.shapereader as shapereader
from matplotlib import rcParams
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import cartopy.io.shapereader as shapereader

定义tif的范围

lons=np.expand_dims(np.arange(112,120,0.05),axis=0).squeeze()
lats=np.expand_dims(np.arange(43,35,-0.05),axis=1).squeeze()

定义坐标

proj1= ccrs.PlateCarree()

其他的一些参数

plot.register_fonts(default=True)
lons=np.expand_dims(np.arange(112,120,0.05),axis=0).squeeze()
lats=np.expand_dims(np.arange(43,35,-0.05),axis=1).squeeze()
proj1= ccrs.PlateCarree()
levels=[0,15,35,55,75,115,160]  #colorbar分级配色的参考
config = {"font.family":'Times New Roman',"font.size":16,"mathtext.fontset":'stix'} #字体及大小定义
rcParams.update(config)

绘图

  • 下面cliped中的三个数字是根据你选择的区域进行确定的,为区域对应的abcode
    在这里插入图片描述
fig, axs = plot.subplots(nrows=3,ncols=4,space=0,proj=proj1,figsize=(6,4))#journal 'nat1'
for i in range(11):
    ds=gdal.Open(files[i])
    arr=ds.ReadAsArray()
    t2=axs[i].contourf(lons,lats,arr,transform=ccrs.PlateCarree(),levels=levels,cmap=cmaps.BlAqGrYeOrReVi200)
    jjj = shapereader.Reader(r'京津冀.shp').geometries()
    axs[i].add_geometries(jjj, ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=1, zorder=1)
    cliped = shp2clip(t2, axs[i], r'京津冀.shp',['110000','120000','130000']) #根据矢量范围进行裁剪
    axs[i].format(latlim=(35,43), lonlim=(112,120),lonlines=2, latlines=2,)   #定义数据框的范围
    name='{}:00'.format(files[i].split(" ")[-1][:-4])

    axs[i].text(117,36,name,fontsize=8)
fig.colorbar(t2,shrink=0.85,orientation='vertical',extend='both',pad=0.25,aspect=30)
plt.delaxes(axs[2,3]) #删除最后一个图
plt.savefig(savepath,dpi=600,bbox_inches='tight')

效果

在这里插入图片描述

cmaps

  • 输入下面的命令,查看不同的colorbar
help(cmaps)

在这里插入图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值