如何用Python绘制天气图
发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,这篇文章主要讲解了"如何用Python绘制天气图",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"如何用Python绘制天气图"吧!#!/bin/env
千家信息网最后更新 2025年12月02日如何用Python绘制天气图
这篇文章主要讲解了"如何用Python绘制天气图",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"如何用Python绘制天气图"吧!
#!/bin/env python#coding=utf-8import codecsimport numpy as npimport datetimeimport reimport pandas as pdimport cartopy.crs as ccrsimport cartopy.feature as cfeaturefrom metpy.calc import wind_componentsfrom metpy.plots import add_metpy_logo, current_weather, sky_cover, StationPlot, wx_code_mapfrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatterfrom metpy.units import unitsimport matplotlib.pyplot as pltfrom matplotlib.patches import Polygonimport cartopy.io.shapereader as shpreaderdef func_return_self(x):return xdef split(str_in, sep=None, convert_func=None):ss = str_in.split(sep)nn = len(ss)rst = [None]*nnif convert_func is None:cf = [func_return_self] * nnelse:cf = [_ for _ in convert_func]# print(nn, len(cf))for i in range(nn):xcf = func_return_self if cf[i] is None else cf[i]rst[i] = xcf(ss[i])return rstdef d1_parse(filename,encoding="gb2312"):"""读micaps第1类数据文件到内存:return:"""with codecs.open(filename, mode='r', encoding=encoding) as fid:contents = fid.readlines()dataflag, style, title = split(contents[0],None,None)nn = len(contents)nx = int((nn-2)/2)data = {"stid":[None]*nx,"lon":[None]*nx,"lat":[None]*nx,"height":[None]*nx,"stlevel":[None]*nx,"cloud":[None]*nx,"wd":[None]*nx,"ws":[None]*nx,"psfc":[None]*nx,"pd3":[None]*nx,"pw1":[None]*nx,"pw2":[None]*nx,"prc6":[None]*nx,"lc1":[None]*nx,"lc2":[None]*nx,"lc3":[None]*nx,"dp":[None]*nx,"njd":[None]*nx,"cw":[None]*nx,"tc":[None]*nx,"mc":[None]*nx,"hc":[None]*nx,"flag1":[None]*nx,"flag2":[None]*nx,"dtc24":[None]*nx,"dp24":[None]*nx}data = pd.DataFrame(data)j=0for i in range(2,nn,2):iline1 = contents[i]iline2 = contents[i+1]iline = " ".join([iline1,iline2])#for iline in contents[2:]:data.stid[j], data.lon[j], data.lat[j], data.height[j], data.stlevel[j],data.cloud[j],data.wd[j],data.ws[j],data.psfc[j],data.pd3[j], data.pw1[j], data.pw2[j], \data.prc6[j], data.lc1[j],data.lc2[j],data.lc3[j], data.dp[j], data.njd[j], data.cw[j], data.tc[j], data.mc[j], data.hc[j], data.flag1[j], data.flag2[j], data.dtc24[j],data.dp24[j] \=split(iline,None,[int, float,float,float,int,float,float,float,float,float,int,int,\float,float,float,float,float,float,int, float,float, float,int, int,float,float])j+=1#data.append([stid, lon, lat, height, stlevel,cloud,wd,ws,psfc,pd3, pw1, pw2,\#prc6, lc1,lc2,lc3, dp, njd, cw, tc, mc, hc, flag1, flag2, dtc24,dp24])#print(data)return dataflag, style, title,datadef d4_parse(filename,encoding="gb2312"):"""读micaps第4类数据文件到内存:return:"""try:file_object = codecs.open(filename, mode='r', encoding=encoding)all_the_text = file_object.read().strip()file_object.close()contents = re.split('[\s]+', all_the_text)if len(contents) < 23:returndataflag = contents[0].strip()style = contents[1].strip()title = contents[2].strip()yy = int(contents[3].strip())mm = int(contents[4].strip())dd = int(contents[5].strip())hh = int(contents[6].strip())forehh = int(contents[7].strip())level = contents[8].strip()deltalon = float(contents[9].strip())deltalat = float(contents[10].strip())beginlon = float(contents[11].strip())endlon = float(contents[12].strip())beginlat = float(contents[13].strip())endlat = float(contents[14].strip())sumlon = int(contents[15].strip())sumlat = int(contents[16].strip())distance = float(contents[17].strip())min = float(contents[18].strip())max = float(contents[19].strip())def1 = contents[20].strip()def2 = contents[21].strip()x = np.arange(beginlon, endlon + 0.9*deltalon, deltalon)y = np.arange(beginlat, endlat + 0.9*deltalat, deltalat)X, Y = np.meshgrid(x, y)if dataflag == 'diamond' and style == '4':begin = 22Z = np.zeros((sumlat, sumlon))for i in range(sumlon):for j in range(sumlat):Z[j, i] = float(contents[begin + j * sumlon + i])return dataflag, style,title,yy,mm,dd,hh,forehh,level,X,Y,Z,distance,min,max,def1,def2except Exception as err:print(u'【{0}】{1}-{2}'.format(filename, err, datetime.datetime.now()))if __name__ == "__main__":dataflag, style, title, yy, mm, dd, hh, forehh, level, X, Y, p0_data, distance, dmin, dmax, def1, def2 = d4_parse("/home/hliang/share/share/plotest/20190126/p0/19012602.000")station_dataflag, staiton_style, station_title, station_data = d1_parse("/home/hliang/share/share/plotest/20190126/plot/19012108.000")station_data = station_data.replace(9999,np.nan)station_data = station_data[station_data.stlevel==2]#.dropna()lat_max=50lat_min=15lon_max=130lon_min=100proj = ccrs.LambertCylindrical(central_longitude=(lon_max+lon_min)/2.0)#ccrs.LambertConformal(central_longitude=(lon_max+lon_min)/2.0, central_latitude=(lat_max+lat_min)/2.0,standard_parallels=[(lat_max+lat_min)/2.0])fig = plt.figure(figsize=(10, 10))ax = fig.add_subplot(1, 1, 1, projection=proj)ax.set_extent([lon_min,lon_max,lat_min,lat_max],proj)ax.set_xticks(range(lon_min,lon_max+2,10), crs=proj)ax.set_yticks(range(lat_min,lat_max+2,10), crs=proj)shp = shpreader.Reader('/home/hliang/share/share/plotest/shp_resources/CHN_adm/CHN_adm1.shp')ax.add_geometries(shp.geometries(), crs=proj, facecolor="none", edgecolor="grey", lw=0.8)contours = ax.contour(X, Y, p0_data,levels=np.arange(dmin,dmax+0.9*distance,distance), colors="black",transform=proj,linewidths=0.5)plt.clabel(contours, fontsize=8,fmt='%.1f')stationplot = StationPlot(ax, station_data['lon'].values, station_data['lat'].values, clip_on=True,transform=proj, fontsize=6)u,v = wind_components(station_data['ws'].values * units('m/s'),station_data['wd'].values * units.degree)stationplot.plot_parameter('NW', station_data['tc'], color='red')stationplot.plot_barb(u, v,sizes=dict(emptybarb=0.15))cw = station_data.cw.replace(np.nan,0).astype(np.int)pw1 = station_data.pw1.replace(np.nan,0).astype(np.int)stationplot.plot_symbol('W', cw, current_weather,color='fuchsia')stationplot.plot_symbol('SE', pw1, current_weather,color='y')'''for record,state in zip(shp.records(), shp.geometries()):name = record.attributes["NAME_1"]if name=="Jiangsu":ax.add_geometries(state,crs=proj,facecolor="none",edgecolor="grey",lw=0.5)'''plt.savefig('./fig1.png',dpi=300)#plt.show()
感谢各位的阅读,以上就是"如何用Python绘制天气图"的内容了,经过本文的学习后,相信大家对如何用Python绘制天气图这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
天气
天气图
学习
内存
内容
数据
文件
就是
思路
情况
文章
更多
知识
知识点
篇文章
跟着
问题
实践
推送
研究
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
惠普服务器引导
数据库技术课程设计心得
金融软件开发信贷操作市场空间
自己创建软件开发团队
太原ar软件开发公司
数据库显示已存储
江苏辅助计算机网络技术服务简介
网络安全要知道的童谣
msde数据库默认端口
软件开发行业财务制度
设备管理的服务器地址是什么
小米路由web服务器
大一新生网络安全专业书籍
福建管理系统软件开发公司
互联网贷款和科技银行
网络安全产品合作
企业信息网络安全培训工作
网络安全协议中SA的作用
八仙购物软件开发
ccf数据库专业委员会简称
软件开发学校在什么地方
查看服务器内存大小
1901网络安全保障工作
耕地后备资源调查数据库技术标准
服务器怎么生成dns
广州优投网络技术服务有限公司
服务器如何保护网站安全
梦幻手游新服务器有什么用
国家网络安全政策2021
虚拟机配置与管理打印服务器