前言
這篇源自在網(wǎng)上看到一張繪制政治正確中國(guó)地圖的帖子,下載了相應(yīng)的數(shù)據(jù)和py腳本雅采,運(yùn)行時(shí)總是報(bào)錯(cuò)砾省,遂逐條檢查修改之后,得到正確的腳本场勤。
原帖鏈接
原帖
https://cloud.tencent.com/developer/article/1484356
修改后的Python腳本
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeat
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from cartopy.io.shapereader import Reader
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import warnings
import os
from cv2 import imread, imshow
def create_map():
extent = [70, 140, 0, 60]
shp_path = '/mnt/c/Users/LEEHQ/Downloads/chinamap/'
# --創(chuàng)建畫(huà)圖空間
proj = ccrs.PlateCarree() # 創(chuàng)建坐標(biāo)系
fig = plt.figure(figsize=(6, 8), dpi=350) # 創(chuàng)建頁(yè)面
ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) # 創(chuàng)建子圖
# --設(shè)置地圖屬性
reader = Reader(shp_path + 'Province_9/Province_9.shp')
provinces = cfeat.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none')
ax.add_feature(provinces, linewidth=1)
ax.set_extent(extent, crs=proj)
# --增加低分辨率地形圖(cartopy自帶)
#ax.stock_img() # 增加地形圖
# --增加高分辨率地形圖(需自行下載)
#fname = os.path.join(config["repo_data_dir"], 'raster', 'natural_earth', '10-natural-earth-1.tif')
fname='/mnt/c/Users/LEEHQ/Downloads/chinamap/NE1_LR_LC_SR_W_DR.tif'
ax.imshow(imread(fname), origin='upper', transform=proj, extent=[-180, 180, -90, 90])
# --設(shè)置網(wǎng)格點(diǎn)屬性
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1.2, color='k', alpha=0.5, linestyle='--')
gl.xlabels_top = False # 關(guān)閉頂端的經(jīng)緯度標(biāo)簽
gl.ylabels_right = False # 關(guān)閉右側(cè)的經(jīng)緯度標(biāo)簽
gl.xformatter = LONGITUDE_FORMATTER # x軸設(shè)為經(jīng)度的格式
gl.yformatter = LATITUDE_FORMATTER # y軸設(shè)為緯度的格式
gl.xlocator = mticker.FixedLocator(np.arange(extent[0], extent[1]+10, 10))
gl.ylocator = mticker.FixedLocator(np.arange(extent[2], extent[3]+10, 10))
return ax
if __name__ == '__main__':
warnings.filterwarnings('ignore')
ax = create_map()
plt.show()