一、效果展示
二、绘图前准备
1.用于绘图的网格数据集
2.地图shapefile文件
3.九段线shapefile文件
4.安装并导入cnmaps包
conda环境安装教程:无需手动安装
conda activate myenvs(自定义环境)
conda install cnmaps
三、python代码
1.导入cnmaps包
from cnmaps import clip_contours_by_map
2.完整绘图代码
import numpy as np
import netCDF4 as nc
import matplotlib as mlp
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import ticker
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import scipy
import os
import xarray as xr
import pandas as pd
import geopandas as gpd
import shapefile as shp
import cmaps
from cartopy.io.shapereader import Reader
from cartopy.util import add_cyclic_point
import cartopy.crs as ccrs
import cartopy.mpl.ticker as cticker
import cartopy.feature as cfeature
from typing import List
from cnmaps import clip_contours_by_map
#读取地图和九段线shapefile文件
China = gpd.read_file('/map/china-shapefiles/china_country.shp')
nine_dotted_line = gpd.read_file('/map/china-shapefiles/china_nine_dotted_line.shp')
#合并两个地理区域
geometry_all = pd.concat([China['geometry'], nine_dotted_line['geometry']], ignore_index=True)
#创建一个figure
fig = plt.figure(figsize=(10,8), dpi=500) #figsize:宽和高(inch) dpi:分辨率
#创建子图
ax1 = fig.add_subplot(1,2,1,projection=ccrs.PlateCarree()) #添加子图:划分为1行*2列—位置1(按行) #projection:投影 PlateCaree-把经纬度当做xy坐标值
FontTitle_dict = {'fontname': 'DejaVu Serif', 'fontsize': 15} #定义标题字体和字号
ax1.set_title(r'Concentration of $PM{2.5}$', fontdict=FontTitle_dict, loc='left')
ax1.set_extent([lon_min, lon_max, lat_min, lat_max],crs=ccrs.PlateCarree()) #设置地图范围为中国大陆范围
ax1.add_geometries(geometry_all,crs = ccrs.PlateCarree(), edgecolor='k', linewidths=1, facecolor='none', zorder=1) #添加地理图形.add_geometries-绘制中国地图
#绘制经纬度网格
xticks = np.arange(lon_min,lon_max, 10.) #x轴等间隔
yticks = np.arange(lat_min, lat_max, 10.) #y轴等差间隔
ax1.set_xticks(xticks, crs=ccrs.PlateCarree()) #设置 x 轴刻度
ax1.set_yticks(yticks, crs=ccrs.PlateCarree()) #设置 y 轴刻度
ax1.xaxis.set_major_formatter(cticker.LongitudeFormatter()) #将 x 轴格式化为经度的格式
ax1.yaxis.set_major_formatter(cticker.LatitudeFormatter()) #将 y 轴格式化为纬度的格式
ax1.gridlines(draw_labels=False, xlocs=xticks, ylocs=yticks, linestyle='-', linewidth=0.5, color='gray') #网格线,draw_labels=True默认添加经纬度标签
ax1.tick_params(direction='out', length=4.5, width=0.8, pad=7, labelsize=8.) #labelsize设置坐标标签大小
#绘制等值线填色图:更改变量
min_lev = 0
max_lev = 20
levels = np.arange(min_lev,max_lev, step=0.5) #指定等值线间隔
cf1 = ax1.contourf(lon, lat, soa, levels=levels, cmap='jet',transform=ccrs.PlateCarree(), extend='both') #注意顺序:lon,lat #extend='both'超出值画颜色
#裁剪填色图
china_polygon = China.geometry.unary_union #china-god.read_file为GeoDataFrame ->unary_union转化为地图多边形
clip_contours_by_map(cf1, china_polygon) #利用polygon对contourf进行裁剪
#绘图部分
ntickers = 4 #设置色标的个数
position = fig.add_axes([0.073, 0.25, 0.45, 0.023])
cbar = fig.colorbar(cf1, cax=position, orientation='horizontal', extend='both', drawedges=False)
cbar.ax.tick_params(labelsize=9, size=0)
cbar.ax.xaxis.set_tick_params(width=1.5, size=4) #设置colorbar的刻度线宽度和长度
cbar.set_label(r'$\mu$g/$m^3$', fontsize=15) #色标单位名称
cbar.locator = ticker.MaxNLocator(nbins=ntickers) #设置刻度值密度-maxNlocator最大的定位器数量
cbar.update_ticks()
plt.show()
``