社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python为兰勃脱投影(Lambert)地图添加经纬度刻度(3)

气象学家 • 2 年前 • 775 次点击  

本文作者:天津气候中心 郝立生 博士/研究员
联系邮箱:hls54515@163.com

总有人问兰勃脱投影加经纬度刻度的问题,我整理一个添加四边刻度线和数值的代码,想怎么加就怎么加,供参考使用。这个代码对普通柱状图同样也适用。
" Created on by Haolishen on 2021.6.2, in TianJin"import numpy as npimport matplotlib.pyplot as pltimport cartopy.crs as ccrsimport cartopy.feature as cfeature from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTERimport warnings;   warnings.filterwarnings('ignore')plt.rcParams['font.family'] ='Times New Roman' plt.rcParams['font.size'] = 12                # 自定义获取经纬度刻度位置函数def get_lambert_ticks(ax, ticks0, tick_location): import shapely.geometry as sgeom xmin,xmax,ymin,ymax = ax.get_extent() lonmin,lonmax,latmin,latmax = ax.get_extent(ccrs.PlateCarree()) axises = {'left': [(xmin, ymin), (xmin, ymax)],'right': [(xmax, ymin), (xmax, ymax)], 'bottom': [(xmin, ymin), (xmax, ymin)], 'top': [(xmin, ymax), (xmax, ymax)],} line_axis = sgeom.LineString(axises[tick_location]) ticks = [] N = 50 for tick1 in ticks0: if( (tick_location.upper()=='TOP') | (tick_location.upper()=='BOTTOM')): xy = np.vstack((np.zeros(N)+tick1, np.linspace(latmin-5, latmax+5, N, endpoint=True))).T elif( (tick_location.upper()=='LEFT') | (tick_location.upper()=='RIGHT')): xy = np.vstack((np.linspace(lonmin-5, lonmax+5, N, endpoint=True), np.zeros(N)+tick1)).T proj_xy = (ax.projection.transform_points(ccrs.Geodetic(), xy[:,0], xy[:,1]))[:,:2] line_lonlat = sgeom.LineString(proj_xy) locs = line_axis.intersection(line_lonlat) if not locs: tick = [None] else: if( (tick_location.upper()=='TOP') | (tick_location.upper()=='BOTTOM')): tick = locs.xy[0] elif( (tick_location.upper()=='LEFT') | (tick_location.upper()=='RIGHT')): tick = locs.xy[1] ticks.append(tick[0]) # 去掉看不到的刻度 ticklabels = ticks0 while True: try: index = ticks.index(None) except ValueError: break ticks.pop(index) ticklabels.pop(index) return ticks, ticklabels# 自定义添加左侧刻度的函数def lambert_yticks_left(ax, ticks, length, width, pad, fontdict=None): " Draw ticks on the left y-axis of a Lamber Conformal projection. " yticks, yticklabels = get_lambert_ticks(ax, ticks, 'left') ax.yaxis.tick_left() ax.set_yticks(yticks) ax.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels],fontdict) ax.tick_params(axis='y',which='major',direction='out',length=length, width=width, pad=pad) return# 自定义添加右侧刻度的函数def lambert_yticks_right(ax, ticks,length, width, pad, fontdict=None): " Draw ticks on the right y-axis of a Lamber Conformal projection. " yticks, yticklabels = get_lambert_ticks(ax, ticks, 'right') ax2 = ax.secondary_yaxis('right') #新建ax3,使ax3与ax2完全相同 ax2.yaxis.tick_right() ax2.set_yticks(yticks) ax2.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels],fontdict) ax2.tick_params(axis='y',which='major',direction='out',length=length, width=width, pad=pad) return# 自定义添加底边刻度的函数def lambert_xticks_bottom(ax, ticks, length, width, pad, fontdict=None): " Draw ticks on the bottom x-axis of a Lambert Conformal projection. " xticks, xticklabels = get_lambert_ticks(ax, ticks, 'bottom') ax.xaxis.tick_bottom() ax.set_xticks(xticks) ax.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xticklabels],fontdict) ax.tick_params(axis='x',which='major',direction='out',length=length, width=width, pad=pad) return# 自定义添加顶部刻度的函数def lambert_xticks_top(ax, ticks, length, width, pad, fontdict=None): " Draw ticks on the top x-axis of a Lambert Conformal projection. " xticks, xticklabels = get_lambert_ticks(ax, ticks, 'top') ax2 = ax.secondary_xaxis('top') #新建ax3,使ax3与ax2完全相同 ax2.xaxis.tick_top() ax2.set_xticks(xticks) ax2.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xticklabels],fontdict) ax2.tick_params(axis='x',which='major',direction='out',length=length, width=width, pad=pad) return#-----------------------------------------------------------------------------# 主程序段proj = ccrs.LambertConformal(central_longitude=110,central_latitude=30.0,standard_parallels=(25,47))extent = [80, 135, 17, 53]#2 设置绘图窗口fig = plt.figure(figsize=(8,6)) #创建页面ax = plt.axes(projection=proj)ax.set_extent(extent, crs=ccrs.PlateCarree()) ax.add_feature(cfeature.OCEAN)ax.add_feature(cfeature.LAND)# 添加经纬网格线# 添加经纬度网格和刻度ax.gridlines(draw_labels=None, xlocs=range(0 ,180,10), ylocs=range(0,90,10), linestyle='--', linewidth=0.25, color='k')xticks = [lon for lon in np.arange(70,160,10)]yticks = [lat for lat in np.arange(0,60,10)] ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)fig.canvas.draw() #这个不能少,调用fig.canvas.draw()函数才能够更新显示lambert_xticks_top(ax, xticks, length=4, width=1.0, pad=0, fontdict={'family':'Times New Roman','size':12,'color':'k','rotation':0} ) lambert_yticks_right(ax, yticks, length=4, width=1.0, pad=2, fontdict={'family':'Times New Roman','size':12,'color':'k','rotation':0} )lambert_xticks_bottom(ax, xticks, length=4, width=1.0, pad=2, fontdict={'family':'Times New Roman','size':12,'color':'k','rotation':0} ) lambert_yticks_left(ax, yticks,   length=4, width=1.0, pad=1, fontdict={'family':'Times New Roman','size':12,'color':'k','rotation':0} )plt.savefig(r'cartopy-lambert-loblat.png',dpi=600,bbox_inches='tight')








声明:欢迎转载、转发本号原创内容,可留言区留言或者后台联系小编(微信:gavin7675)进行授权。气象学家公众号转载信息旨在传播交流,其内容由作者负责,不代表本号观点。文中部分图片来源于网络,如涉及作品内容、版权和其他问题,请后台联系小编处理。

   欢迎加入气象学家交流群   

请备注:姓名/昵称-单位/学校-研究方向



往期推荐

 ERA5-Land陆面高分辨率再分析数据(32TB)

★ NASA最新版本CMIP6降尺度数据集30TB

★ ERA5常用变量再分析数据(26TB)

 EC数据商店推出Python在线处理工具箱

★ EC打造实用气象Python工具Metview

 TRMM 3B42降水数据(Daily/3h)

 科研数据免费共享: GPM卫星降水数据

 气象圈子有人就有江湖,不要德不配位!

 请某气象公众号不要 “以小人之心,度君子之腹”!

★ 机器学习简介及在短临天气预警中的应用

★ AMS推荐|气象学家-海洋学家的Python教程

★ Nature-地球系统科学领域的深度学习及理解

★ 采用神经网络与深度学习来预报降水、温度

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/150149
 
775 次点击