基于CNMAPS的地圖白化

用了氣象家園大佬的shp2clip函數(shù)繁扎,他是基于basemap寫的育勺,我稍微修改了一下
直接上白化函數(shù)

import shapefile
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from shapely.geometry import Point as ShapelyPoint
from shapely.geometry import Polygon as ShapelyPolygon
from collections import Iterable
def shp2clip(originfig,ax,shpfile,region, clabel = None, vcplot = None):
    print('your mask region=',region)
    sf = shapefile.Reader(shpfile)
    vertices = []
    codes = []
    for shape_rec in sf.shapeRecords():
        ####這里需要找到和region匹配的唯一標(biāo)識(shí)符线定,record[]中必有一項(xiàng)是對(duì)應(yīng)的野建。
         if shape_rec.record[3] in region:   #####
        #if shape_rec.record[1] in region:  #####
            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)

    if vcplot:
        if isinstance(originfig,Iterable):
            for ivec in originfig:
                ivec.set_clip_path(clip)
        else:
            originfig.set_clip_path(clip)
    else:
        for contour in originfig.collections:
            contour.set_clip_path(clip)

    if  clabel:
        clip_map_shapely = ShapelyPolygon(vertices)
        for text_object in clabel:
            if not clip_map_shapely.contains(ShapelyPoint(text_object.get_position())):
                text_object.set_visible(False)    

    return clip

這里利用cnmaps來白化属划,cnmaps是真的香,簡單暴力候生,沒有的直接pip install cnmaps
傳統(tǒng)的方法是根據(jù)shape文件讀取里面的地理信息同眯,匹配,裁剪

import numpy
import netCDF4 as nc
import sys, os
import cartopy.crs as crs
import cartopy.crs as ccrs
from cnmaps import get_adm_maps, draw_maps
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

box   = [95, 135, 15, 45]
xstep = 15    #x axis step
ystep = 15    #y axis step
fig=plt.figure(num=1,figsize=(8.5,7))   ###????.fig
axlevel1 = [0.1, 0.1, 0.65, 0.8]

#using cnmap
draw_maps(get_adm_maps(level='國')) 
draw_maps(get_adm_maps(level='省'),linewidth=0.3,color='gray') 
plt.axis(box)
ax = plt.gca()

c1=plt.contourf(lon,lat,isop,cmap= plt.cm.get_cmap('jet') )

#below is maskwhite
shpfile='/home/wangnan/data/baihua/country1.shp'
shp2clip(c1, ax, shpfile,'China',clabel=None,vcplot=None)
#ax.add_geometries(shapereader.Reader(shpfile).geometries(), crs=cart_proj, facecolor='none',edgecolor='k',linewidth=2.5)

#axis setting
ax.set_xticks(np.arange(box[0], box[1] + xstep, xstep), )
ax.set_yticks(np.arange(20, 40 + ystep, ystep), )
ax.set_xlim(box[0], box[1])
ax.set_ylim(box[2], box[3])
lon_formatter = LongitudeFormatter(zero_direction_label=False)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
ax.tick_params(labelsize=22)
image.png

那么問題來了陶舞,我要是沒有地圖shape文件咋整嗽测? 自己造一個(gè)唄。
其實(shí)肿孵,基于cnmaps使得這個(gè)很容易實(shí)現(xiàn)
以廣東省為例, 以geopandas的GeoDataFrame格式返回唠粥,可以向engine參數(shù)傳入'goepandas'。

from cnmaps import get_adm_maps,get_adm_names
prov=get_adm_maps(level='省',engine='geopandas')
prov
image.png

該shape文件可以直接保存

prov.to_file('/home/wangnan/data/shapefile2/wnProvince.shp',encoding='utf-8')

好了, 省級(jí)地圖做好了 停做。
由于shp2clip函數(shù)需要讀取地形文件,它是按region來匹配的晤愧,所以我要看看我的region在第幾列

shpfile2= '/home/wangnan/data/shapefile2/wnProvince.shp'  
sf = shapefile.Reader(shpfile2)
for shape_rec in sf.shapeRecords():
    print (shape_rec.record)
image.png

在第2列,所以要把shape2clip的if判斷中的if shape_rec.record[3] in region換成1蛉腌,然后畫圖實(shí)驗(yàn)一下

import numpy
import netCDF4 as nc
import sys, os,cmaps
import cartopy.crs as crs
import cartopy.crs as ccrs
from cnmaps import get_adm_maps, draw_maps
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import matplotlib.colors as colors
box   = [109, 118, 19, 26]
xstep = 3    #x axis step
ystep = 3    #y axis step
fig=plt.figure(num=1,figsize=(8.5,7))   ###????.fig

draw_maps(get_adm_maps(province='廣東省')) 
plt.axis(box)
ax = plt.gca()

cmap_color = cmaps.WhiteBlueGreenYellowRed   #WhiteGreen
c1=ax.contourf(lon,lat,terp,cmap=cmap_color )

#below is maskwhite
shpfile2= '/home/wangnan/data/shapefile2/wnProvince.shp'
region=['廣東省']
shp2clip(c1, ax, shpfile2,region,clabel=None,vcplot=None)

#axis setting
ax.set_xlim(box[0], box[1])
ax.set_ylim(box[2], box[3])
lon_formatter = LongitudeFormatter(zero_direction_label=False)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
ax.tick_params(labelsize=22)
image.png

大功告成

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載官份,如需轉(zhuǎn)載請通過簡信或評(píng)論聯(lián)系作者只厘。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市舅巷,隨后出現(xiàn)的幾起案子羔味,更是在濱河造成了極大的恐慌,老刑警劉巖钠右,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赋元,死亡現(xiàn)場離奇詭異,居然都是意外死亡飒房,警方通過查閱死者的電腦和手機(jī)搁凸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來狠毯,“玉大人护糖,你說我怎么就攤上這事〗浪桑” “怎么了嫡良?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長献酗。 經(jīng)常有香客問我皆刺,道長,這世上最難降的妖魔是什么凌摄? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮漓帅,結(jié)果婚禮上锨亏,老公的妹妹穿的比我還像新娘。我一直安慰自己忙干,他們只是感情好器予,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捐迫,像睡著了一般乾翔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上施戴,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天反浓,我揣著相機(jī)與錄音,去河邊找鬼赞哗。 笑死雷则,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的肪笋。 我是一名探鬼主播月劈,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼度迂,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了猜揪?” 一聲冷哼從身側(cè)響起惭墓,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎而姐,沒想到半個(gè)月后腊凶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡毅人,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年吭狡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丈莺。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡划煮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出缔俄,到底是詐尸還是另有隱情弛秋,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布俐载,位于F島的核電站蟹略,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏遏佣。R本人自食惡果不足惜挖炬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望状婶。 院中可真熱鬧意敛,春花似錦、人聲如沸膛虫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽稍刀。三九已至撩独,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間账月,已是汗流浹背综膀。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捶障,地道東北人僧须。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像项炼,于是被迫代替她去往敵國和親担平。 傳聞我的和親對(duì)象是個(gè)殘疾皇子示绊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容