cartopy画地图需要输入多行命令,有点占code. 所以把控制地图的命令封装成函数,直接调用。
#通用设置
box=[100,135,15,50]
xstep=10
ystep=10
isprovince=1
proj=ccrs.PlateCarree()
#创建画布
fig = plt.figure(figsize=(15, 12))
axlevel=[0.1, 0.66, 0.5, 0.5]
ax1 = plt.axes(axlevel,projection=ccrs.PlateCarree())
MyMap.plot_cnmaps(ax1,axlevel,box,xstep,ystep,isprovince)
ax1.set_extent(box, crs=ccrs.PlateCarree())
早期版本
box = [109, 118, 20, 26]
#box = [110, 115.3, 28, 24.5] #prd region
xstep = 2 #x axis step
ystep = 2 #y axis step
fig=plt.figure(num=1,figsize=(8,7)) ###????.fig
axlevel1 = [0.1, 0.1, 0.65, 0.8]
maps.province_country_map(box=box,axlevel=axlevel1, xstep=xstep, ystep=ystep, labelon='on')
调用函数需
import sys
sys.path.append('C:\\Users\\kima2\\Desktop\python script\\')
import MyMap,maps
plot_cnmaps函数,
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import os
import pandas as pd
import numpy as np
from pathlib import Path
from typing import List
from typing import Union
from typing import Tuple
from matplotlib.collections import LineCollection
import cartopy.crs as ccrs
import cmaps
def plot_cnmaps(ax,axlevel,box,xstep,ystep,isprovince):
#设置ax的范围
# axlevel=[0.1, 0.1, 0.6, 0.5] #ax的大小
# box=[100,135,10,50]
# xstep=10
# ystep=5
#ax = plt.axes(axlevel,projection=ccrs.PlateCarree())
ax.set_extent(box, crs=ccrs.PlateCarree())
#为ax添加海岸线和陆地
ax.coastlines()
#ax.add_feature(cfeature.LAND,alpha=0) #添加大陆特征
#添加中国地图
fname1 = 'C:\\Users\\kima2\\Desktop\\python script\\NCL-Chinamap-master\\NCL-Chinamap-master\\cnmap\\cnmap.shp'
shape_feature1 = cfeature.ShapelyFeature(Reader(fname1).geometries(),
ccrs.PlateCarree(), facecolor='none', edgecolor='k')
ax.add_feature(shape_feature1)
#添加省份
if isprovince==1:
fname2 = 'C:\\Users\\kima2\\Desktop\\python script\\NCL-Chinamap-master\\NCL-Chinamap-master\\cnmap\\cnhimap.shp'
shape_feature2 = cfeature.ShapelyFeature(Reader(fname2).geometries(),
ccrs.PlateCarree(), facecolor='none', edgecolor='gray',linewidth=0.5)
ax.add_feature(shape_feature2)
#为ax1添加地理经纬度标签及刻度
ax.set_xticks(np.arange(box[0],box[1],xstep), crs=ccrs.PlateCarree())
ax.set_yticks(np.arange(box[2]+ystep,box[3],ystep), crs=ccrs.PlateCarree())
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
plt.tick_params(labelsize=20)