Python绘制地理图--Cartopy基础
生活随笔
收集整理的這篇文章主要介紹了
Python绘制地理图--Cartopy基础
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
常用地圖底圖的繪制一般由Basemap或者cartopy模塊完成,由于Basemap庫(kù)是基于python2開(kāi)發(fā)的一個(gè)模塊,目前已經(jīng)不開(kāi)發(fā)維護(hù)。故簡(jiǎn)單介紹cartopy模塊的一些基礎(chǔ)操作。
將地球三維球體投影到二維面上,減少失真。主要方式有默認(rèn)投影(PlateCarree)、蘭勃脫投影(Lambert)、墨卡托投影(Mercator)、極投影。
例一:
import cartopy.crs as ccrs import matplotlib.pyplot as plt#plt.axes是創(chuàng)建一個(gè)軸(或者說(shuō)是主體) projection參數(shù)可以理解為將三維的地理信息如何投影為二維的地理信息,這個(gè)時(shí)候參數(shù)的值就是投影方式,此時(shí)是常用的平面投影 ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() #這個(gè)函數(shù)是在主體上添加了海岸線# Save the plot by calling plt.savefig() BEFORE plt.show() plt.savefig('coastlines.pdf') plt.savefig('coastlines.png')plt.show() #將圖像顯示出來(lái)以上代碼是第一個(gè)例子,例子的運(yùn)行結(jié)果如下
例二:
import cartopy.crs as ccrs import matplotlib.pyplot as pltax = plt.axes(projection=ccrs.Mollweide()) #這里和上一個(gè)例子更換了投影方式,投影成了橢圓形 ax.stock_img() #這個(gè)方法可以認(rèn)為是添加了貼紙,讓海洋呈現(xiàn)藍(lán)色,將陸地和海洋分開(kāi) plt.show()?以上代碼的運(yùn)行結(jié)果如下:
?例三:
import cartopy.crs as ccrs import matplotlib.pyplot as pltax = plt.axes(projection=ccrs.PlateCarree()) ax.stock_img()ny_lon, ny_lat = -75, 43 #這里是倫敦的經(jīng)緯度 delhi_lon, delhi_lat = 77.23, 28.61 #這里是紐約的經(jīng)緯度 #接下來(lái)是要在這兩個(gè)點(diǎn)上畫(huà)線加注釋文字plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],color='blue', linewidth=2, marker='o',transform=ccrs.Geodetic(),) #前面兩個(gè)參數(shù)是線的起始點(diǎn)的經(jīng)緯度,最后一個(gè)參數(shù)是用來(lái)指定數(shù)據(jù)的坐標(biāo)系, 一般來(lái)說(shuō),數(shù)據(jù)的坐標(biāo)系與這個(gè)整體軸的坐標(biāo)系是相同的,我們也可以設(shè)置為不同,此時(shí)整體是平面坐標(biāo)系,數(shù)據(jù)設(shè)置為了橢圓坐標(biāo)系,就是在橢圓中這兩個(gè)點(diǎn)畫(huà)個(gè)直線應(yīng)該是什么樣的plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],color='gray', linestyle='--',transform=ccrs.PlateCarree(),)plt.text(ny_lon - 3, ny_lat - 12, 'New York',horizontalalignment='right',transform=ccrs.Geodetic())plt.text(delhi_lon + 3, delhi_lat - 12, 'Delhi',horizontalalignment='left',transform=ccrs.Geodetic())plt.show()以上代碼的結(jié)果如下所示:
通過(guò)這三個(gè)小例子我們了解到了一些皮毛,接著往下走。
在這個(gè)例子中我們學(xué)習(xí)1.如何繪制坐標(biāo)系 2.如何顯示區(qū)域地圖
import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatterax=plt.axes(projection=ccrs.PlateCarree(central_longitude=0)) #這里設(shè)置了中心經(jīng)線參數(shù),就是說(shuō)我們這個(gè)圖的中心線在哪 ax.stock_img() ax.coastlines()#設(shè)置坐標(biāo)軸標(biāo)簽 ax.set_xticks(np.arange(0,361,40), crs=ccrs.PlateCarree()) #設(shè)置緯度范圍及其間隔,以及投影方式 ax.set_yticks(np.arange(-90,90+30,30), crs=ccrs.PlateCarree()) #zero_direction_label用來(lái)設(shè)置經(jīng)度的0度加不加E和W lon_formatter = LongitudeFormatter(zero_direction_label=False) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) #設(shè)置坐標(biāo)軸標(biāo)簽的格式,加上N,S,E,W ax.grid() #添加網(wǎng)格線#設(shè)置坐標(biāo)軸的粗細(xì) ax.outline_patch.set_visible(False) ax.spines['bottom'].set_visible(True) ax.spines['left'].set_visible(True) ax.spines['right'].set_visible(True) ax.spines['top'].set_visible(True) #設(shè)置四個(gè)邊框可不可視 ax.spines['bottom'].set_linewidth(2.5);###設(shè)置底部坐標(biāo)軸的粗細(xì) ax.spines['left'].set_linewidth(2.5);####設(shè)置左邊坐標(biāo)軸的粗細(xì) ax.spines['right'].set_linewidth(2.5);###設(shè)置右邊坐標(biāo)軸的粗細(xì) ax.spines['top'].set_linewidth(2.5);####設(shè)置上部坐標(biāo)軸的粗細(xì)#之前都是繪制的默認(rèn)的全球地圖,此時(shí)繪制區(qū)域地圖 ax.set_extent([40,180,0,90],crs=ccrs.PlateCarree()) #第一個(gè)參數(shù)是繪制區(qū)域,起始經(jīng)度,起始緯度 第二個(gè)參數(shù)是投影類型 plt.show()接下來(lái)這個(gè)例子告訴我們?cè)趫D的基礎(chǔ)上添加一些新的元素(湖泊等)
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeatureproj = ccrs.PlateCarree() fig = plt.figure(figsize=(15, 7)) ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) #可以看見(jiàn)此處設(shè)置主題軸的方式跟之前有所不同,此時(shí)是用ccrs和plt混合的方式來(lái)定義的,先用plt來(lái)設(shè)置整體大小,再來(lái)設(shè)置主軸 ax.coastlines()#在原來(lái)圖的基礎(chǔ)上加上一些標(biāo)簽 ax.add_feature(cfeature.LAND) # 添加陸地 ax.add_feature(cfeature.COASTLINE,lw=0.3)# 添加海岸線 ax.add_feature(cfeature.RIVERS,lw=0.25)# 添加河流 ax.add_feature(cfeature.LAKES)# 添加湖泊 ax.add_feature(cfeature.BORDERS, linestyle='-',lw=0.25)# 不推薦,我國(guó)丟失了藏南、臺(tái)灣等領(lǐng)土 ax.add_feature(cfeature.OCEAN)#添加海洋 #ax.add_feature(cfeature.OCEAN,color='green')#添加海洋,我們還可以設(shè)置一些參數(shù)改變默認(rèn)設(shè)置,主要修改lw、linestyle、color這三個(gè)參數(shù)#設(shè)置經(jīng)緯度 gl = ax.gridlines(draw_labels=True, linewidth=0.2, color='k', alpha=0.5, linestyle='--') # 調(diào)節(jié)字體大小 gl.xlabel_style={'size':12.5} gl.ylabel_style={'size':12.5}#設(shè)置高精度 會(huì)出現(xiàn)地圖上本來(lái)沒(méi)有的一些小島 ax.add_feature(cfeature.COASTLINE.with_scale('10m'),lw=0.5)繪制中國(guó)地圖:
重點(diǎn)是從文件中讀取CN-border-La.da文件,目的是讀取里面每個(gè)點(diǎn)的經(jīng)緯度,用于給底圖加上行政邊界。代碼如下:
import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature#讀取CN-border-La.dat文件 with open('D:/繪制地圖/CN-border-La.dat') as src:context = src.read()blocks = [cnt for cnt in context.split('>') if len(cnt) > 0]borders = [np.fromstring(block, dtype=float, sep=' ') for block in blocks] #設(shè)置畫(huà)圖各種參數(shù) fig = plt.figure(figsize=[8, 8]) # 設(shè)置投影類型和經(jīng)緯度 ax = plt.axes(projection=ccrs.LambertConformal(central_latitude=90,central_longitude=105)) # 畫(huà)海,陸地,河流,湖泊 ax.add_feature(cfeature.OCEAN.with_scale('50m')) ax.add_feature(cfeature.LAND.with_scale('50m')) ax.add_feature(cfeature.RIVERS.with_scale('50m')) ax.add_feature(cfeature.LAKES.with_scale('50m')) # 畫(huà)國(guó)界 for line in borders:ax.plot(line[0::2], line[1::2], '-', color='gray',transform=ccrs.Geodetic()) # 畫(huà)經(jīng)緯度網(wǎng)格 ax.gridlines(linestyle='--') # 框出區(qū)域 ax.set_extent([80, 140, 13, 55]) # 畫(huà)南海,這一步是新建一個(gè)ax,設(shè)置投影 sub_ax = fig.add_axes([0.741, 0.11, 0.14, 0.155],projection=ccrs.LambertConformal(central_latitude=90,central_longitude=115)) # 畫(huà)海,陸地,河流,湖泊 sub_ax.add_feature(cfeature.OCEAN.with_scale('50m')) sub_ax.add_feature(cfeature.LAND.with_scale('50m')) sub_ax.add_feature(cfeature.RIVERS.with_scale('50m')) sub_ax.add_feature(cfeature.LAKES.with_scale('50m')) # 畫(huà)邊界 for line in borders:sub_ax.plot(line[0::2], line[1::2], '-', color='gray',transform=ccrs.Geodetic()) # 框區(qū)域 sub_ax.set_extent([105, 125, 0, 25]) # 顯示 plt.show()效果圖如下:
?
總結(jié)
以上是生活随笔為你收集整理的Python绘制地理图--Cartopy基础的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国智能互动纺织品市场趋势报告、技术动态
- 下一篇: 熊猫烧香简介