Python自学笔记——Matplotlib风羽自定义_第1页
Python自学笔记——Matplotlib风羽自定义_第2页
已阅读5页,还剩5页未读 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Python自学笔记Matplotlib风羽自定义对于气象专业的小学生来说,风场是预报重要的参考数据,我们所知的风羽有四种:短线代表风速2m/s,长线代表风速4m/s,空心三角代表风速20m/s,实心三角代表风速50m/s。而matplotlib的风羽只有短线、长线、三角三种,而这里的三角不分空心实心,但是可通过改变风羽颜色为白色使三角变为空心形状,虽然这三种可以自定义各自代表的风速,但是仍与我们的使用习惯不符,即使把三角设成20m/s,原本一个实心三角就能表示的50m/s的风在matplotlib中需要两个三角外加两条长线一条短线。为了迎合预报员的需求,我在研究了matplotlib的风场函

2、数barbs()的源代码quiver.py文件后,对quiver.py做了适当的调整,使得matplotlib也有了空心三角和实心三角之分。一、函数barbs的使用barb(X,Y,U,V,*kw)X:风场数据X坐标Y:风场数据Y坐标U:风的水平方向分量V:风的垂直方向分量Demonstrationofwindbarbplotsimportmatplotlib.pyplotaspltimportnumpyasnpx=np.linspace(-5,5,5)X,Y=np.meshgrid(x,x)U,V=12*X,12*Ydata=(-1.5,.5,-6,-6),(1,-1,-46,46),(-3

3、,-1,11,-11),(1,1.5,80,80),(0.5,0.25,25,15),(-1.5,-0.5,-5,40)data=np.array(data,dtype=('x',np.float32),('y',np.float32),('u',np.float32),('v',np.float32)# Defaultparameters,uniformgridax=plt.subplot(2,2,1)ax.barbs(X,Y,U,V)# Arbitrarysetofvectors,makethemlongerandchange

4、thepivotpoint#(pointaroundwhichthey'rerotated)tobethemiddleax=plt.subplot(2,2,2)ax.barbs(data'x',data'y',data'u',data'v',length=8,pivot='middle')# Showingcolormappingwithuniformgrid.Fillthecircleforanemptybarb,# don'troundthevalues,andchangesomeofthesi

5、zeparametersax=plt.subplot(2,2,3)ax.barbs(X,Y,U,V,np.sqrt(U*U+V*V),fill_empty=True,rounding=False,sizes=dict(emptybarb=0.25,spacing=0.2,height=0.3)# Changecolorsaswellastheincrementsforpartsofthebarbsax=plt.subplot(2,2,4)ax.barbs(data'x',data'y',data'u',data'v',flagco

6、lor='r',barbcolor='b','g',barb_increments=dict(half=10,full=20,flag=100),flip_barb=True)plt.show()二、源代码解读1. classBarbs()classBarbs(mcollections.PolyCollection):erpddef_init_(self,ax,*args,*kw):def_find_tails(self,mag,rounding=True,half=5,full=10,flag=50):def_make

7、_barbs(self,u,v,nflags,nbarbs,half_barb,empty_flag,length,pivot,sizes,fill_empty,flip):defset_UVC(self,U,V,C=None):defset_offsets(self,xy):通过读源代码可知类Barbs有五个方法分别为_init_、_find_tails、_make_barbs、set_UVC、set_offsets。2. _init_erpddef_init_(self,ax,*args,*kw):Theconstructortakesonerequiredarg

8、ument,anAxesinstance,followedbytheargsandkwargsdescribedbythefollowingpylabinterfacedocumentation:%(barbs_doc)sself._pivot=kw.pop('pivot','tip')self._length=kw.pop('length',7)barbcolor=kw.pop('barbcolor',None)flagcolor=kw.pop('flagcolor',None)self.sizes=kw.pop

9、('sizes',dict()self.fill_empty=kw.pop('fill_empty',False)self.barb_increments=kw.pop('barb_increments',dict()self.rounding=kw.pop('rounding',True)self.flip=kw.pop('flip_barb',False)transform=kw.pop('transform',ax.transData)#Flagcolorandandbarbcolorprov

10、ideconvenienceparametersfor#settingthefacecolorandedgecolor,respectively,ofthebarb#polygon.Wealsoworkheretomaketheflagthesamecolorasthe#restofthebarbbydefaultifNonein(barbcolor,flagcolor):kw'edgecolors'='face'ifflagcolor:kw'facecolors'=flagcolorelifbarbcolor:kw'facecolors

11、'=barbcolorelse:#Settofacecolorpassedinordefaulttoblackkw.setdefault('facecolors','k')else:kw'edgecolors'=barbcolorkw'facecolors'=flagcolor#Parseoutthedataarraysfromthevariousconfigurationssupportedx,y,u,v,c=_parse_args(*args)self.x=xself.y=yxy=np.hstack(x:,np.new

12、axis,y:,np.newaxis)#Makeacollectionbarb_size=self._length*2/4#Empiricallydeterminedmcollections.PolyCollection._init_(self,(barb_size,),offsets=xy,transOffset=transform,*kw)self.set_transform(transforms.IdentityTransform()self.set_UVC(u,v,c)_init_()方法为初始化方法,此方法中flagcolor、barbcolor为设置风羽颜色的关键字,中间的说明文字

13、提示颜色设置是针对所有的风羽的,所以通过颜色设置达不到风羽中既有空心白色三角又有实心黑色三角。初始化方法中在对一些参数进行了初始化赋值后执行了set_UVC()方法,所以我们顺着这个set_UVC()方法往下继续读。3. set_UVC()defset_UVC(self,U,V,C=None):self.u=ma.masked_invalid(U,copy=False).ravel()self.v=ma.masked_invalid(V,copy=False).ravel()ifCisnotNone:c=ma.masked_invalid(C,copy=False).ravel()x,y,u,

14、v,c=delete_masked_points(self.x.ravel(),self.y.ravel(),self.u,self.v,c)else:x,y,u,v=delete_masked_points(self.x.ravel(),self.y.ravel(),self.u,self.v)magnitude=np.hypot(u,v)flags,emptyflags,barbs,halves,empty=self._find_tails(magnitude,self.rounding,*self.barb_increments)#Gettheverticesforeachoftheba

15、rbsplot_barbs=self._make_barbs(u,v,flags,emptyflags,barbs,halves,empty,self._length,self._pivot,self.sizes,self.fill_empty,self.flip)self.set_verts(plot_barbs)#SetthecolorarrayifCisnotNone:self.set_array(c)#Updatetheoffsetsincasethemaskeddatachangedxy=np.hstack(x:,np.newaxis,y:,np.newaxis)self._offs

16、ets=xyself.stale=True在此方法中,首先进行了变量的命名赋值,然后依次执行了方法_find_tails和_make_barbs。_make_barbs的输入为_find_tails的输出,find_tails的输入中有一个为magnitude=np.hypot(u,v),np.hypot()为勾股定理方法,因此可知magnitude为风速。4. _find_tailsdef_find_tails(self,mag,rounding=True,half=5,full=10,flag=50):Findhowmanyofeachofthetailpiecesisnecessary.

17、Flagspecifiestheincrementforaflag,barbforafullbarb,andhalfforhalfabarb.Magshouldbethemagnitudeofavector(i.e.,>=0).Thisreturnsatupleof:(*numberofflags*,*numberofbarbs*,*half_flag*,*empty_flag*)*half_flag*isabooleanwhetherhalfofabarbisneeded,sincethereshouldonlyeverbeonehalfonagivenbarb.*empty_flag

18、*flagisanarrayofflagstoeasilytellifabarbisempty(toolowtoplotanybarbs/flags.# Ifrounding,roundtothenearestmultipleofhalf,thesmallest# incrementifrounding:mag=half*(mag/half+0.5).astype()num_flags=np.floor(mag/flag).astype()mag=np.mod(mag,flag)num_barb=np.floor(mag/full).astype()mag=

19、np.mod(mag,full)half_flag=mag>=halfempty_flag=(half_flag|(num_flags>0)|(num_emptyflags>0)|(num_barb>0)returnnum_flags,num_barb,half_flag,empty_flag通过读此方法的说明文档可知,此方法作用为根据输入的风速、设置的短线长线三角的数值计算并返回三角、长线、短线的个数以及有没有无风的情况。5. _make_barbsdef_make_barbs(self,u,v,nflags,nbarbs,half_barb,empty_flag,l

20、ength,pivot,sizes,fill_empty,flip):Thisfunctionactuallycreatesthewindbarbs.*u*and*v*arecomponentsofthevectorinthe*x*and*y*directions,respectively.*nflags*,*nbarbs*,and*half_barb*,empty_flag*are,*respectively,thenumberofflags,numberofbarbs,flagfor*halfabarb,andflagforemptybarb,ostensiblyobtained*from

21、:meth:'_find_tails'.*length*isthelengthofthebarbstaffinpoints.*pivot*specifiesthepointonthebarbaroundwhichtheentirebarbshouldberotated.Rightnow,validoptionsare'head'and'middle'.*sizes*isadictionaryofcoefficientsspecifyingtheratioofagivenfeaturetothelengthofthebarb.Thesefeatur

22、esinclude:- *spacing*:spacebetweenfeatures(flags,full/halfbarbs)- *height*:distancefromshaftoftopofaflagorfullbarb- *width*-widthofaflag,twicethewidthofafullbarb- *emptybarb*-radiusofthecircleusedforlowmagnitudes*fill_empty*specifieswhetherthecirclerepresentinganemptybarbshouldbefilledornot(thischan

23、gesthedrawingofthepolygon).*flip*isaflagindicatingwhetherthefeaturesshouldbeflippedtotheothersideofthebarb(usefulforwindsinthesouthernhemisphere.Thisfunctionreturnslistofarraysofvertices,definingapolygonforeachofthewindbarbs.Thesepolygonshavebeenrotatedtoproperlyalignwiththevectordirection.#Thesecon

24、trolthespacingandsizeofbarbelementsrelativetothe#lengthoftheshaftspacing=length*sizes.get('spacing',0.125)full_height=length*sizes.get('height',0.4)full_width=length*sizes.get('width',0.25)empty_rad=length*sizes.get('emptybarb',0.15)#Controlsypointwheretopivotthebarb.

25、pivot_points=dict(tip=0.0,middle=-length/2.)#Checkforflipifflip:full_height=-full_heightendx=0.0endy=pivot_pointspivot.lower()#Gettheappropriateangleforthevectorcomponents.Theoffsetis#duetothewaythebarbisinitiallydrawn,goingdownthey-axis.#Thismakessenseinameteorologicalmodeofthinkingsincethere0#degr

26、eescorrespondstonorth(they-axistraditionally)angles=-(ma.arctan2(v,u)+np.pi/2)#Usedforlowmagnitude.Wejustgetthevertices,soifwemakeit#outhere,itcanbereused.Thecentersethereshouldputthe#centerofthecircleatthelocation(offset),ratherthanatthe#samepointasthebarbpivot;thisseemsmoresensible.circ=CirclePoly

27、gon(0,0),radius=empty_rad).get_verts()iffill_empty:empty_barb=circelse:#Ifwedon'twanttheemptyonefilled,wemakeadegenerate#polygonthatwrapsbackoveritselfempty_barb=np.concatenate(circ,circ:-1)barb_list=forindex,angleinnp.ndenumerate(angles):#Ifthevectormagnitudeistooweaktodrawanything,plotan#empty

28、circleinsteadifempty_flagindex:#Wecanskipthetransformsincethecirclehasnopreferred#orientationbarb_list.append(empty_barb)continuepoly_verts=(endx,endy)offset=length#Addverticesforeachflagforiinrange(nflagsindex):#Thespacingthatworksforthebarbsisalittletomuchfor#theflags,butthisonlyoccurswhenwehavemo

29、rethan1#flag.ifoffset!=length:offset+=spacing/2.poly_verts.extend(endx,endy+offset,endx+full_height,endy-full_width/2+offset,endx,endy-full_width+offset)offset-=full_width+spacing#Addverticesforeachbarb.Thesereallyarelines,butworks#greatadding3verticesthatbasicallypullthepolygonoutand#backdownthelin

30、eforiinrange(nbarbsindex):poly_verts.extend(endx,endy+offset),(endx+full_height,endy+offset+full_width/2),(endx,endy+offset)offset-=spacing#Addtheverticesforhalfabarb,ifneededifhalf_barbindex:#Ifthehalfbarbisthefirstonthestaff,traditionallyit#isoffsetfromtheendtomakeiteasytodistinguishfroma#barbwith

31、afulloneifoffset=length:poly_verts.append(endx,endy+offset)offset-=1.5*spacingpoly_verts.extend(endx,endy+offset),(endx+full_height/2,endy+offset+full_width/4),(endx,endy+offset)#Rotatethebarbaccordingtheangle.Makingthebarbfirstand#thenrotatingitmadethemathfordrawingthebarbreallyeasy.#Also,thetransf

32、ormframeworkmakesdoingtherotationsimple.poly_verts=transforms.Affine2D().rotate(-angle).transform(poly_verts)barb_list.append(poly_verts)returnbarb_list通过读此方法的说明文档可知,此方法作用为根据输入的风数据以及短线长线三角的个数绘制风羽风向杆。绘制过程为:判断地图坐标点是不是无风,如果无风就绘制一个空心圆圈代表。如果有风就开始按照三角、长线、短线的顺序绘制。绘制方法为:创建一个用于存储关键点坐标的列表poly_verts计算关键点坐标通过tr

33、ansform方法将关键点坐标列表中的各个关键点依次用黑线连接起来,最终将风羽风向杆绘制出来此方法的几个关键变量:spacing:风羽上短线长线以及三角间的距离full_height:三角的高度full_width:三角的宽度endx:风羽绘制的起始点x坐标endy:风羽绘制的起始点y坐标angles:风向杆角度poly_verts:绘制风羽风向杆的关键点列表offset:绘制完一个三角或线后下一个三角或线的关键起始坐标poly_verts=(endx,endy)offset=length#Addverticesforeachflagforiinrange(nflagsindex):# The

34、spacingthatworksforthebarbsisalittletomuchfor# theflags,butthisonlyoccurswhenwehavemorethan1# flag.ifoffset!=length:offset+=spacing/2.poly_verts.extend(endx,endy+offset,endx+full_height,endy-full_width/2+offset,endx,endy-full_width+offset)offset-=full_width+spacing这一段是绘制风羽的主要代码,利用图片的形式说明三、绘制空心实心三角在了

35、解了风羽的绘制过程后,发现可以通过增加关键点直接绘制实心三角,通过原绘制方法绘制空心三角。1. 实心三角绘制实心三角绘制代码#Addverticesforeachflagforiinrange(nflagsindex):#Thespacingthatworksforthebarbsisalittletomuchfor#theflags,butthisonlyoccurswhenwehavemorethan1#flag.ifoffset!=length:offset+=spacing/2.poly_verts.extend(endx,endy+offset,endx+full_height/4,

36、endy-full_width/8+offset,endx,endy-full_width/8+offset,endx+full_height/4,endy-full_width/8+offset,endx+full_height/2,endy-full_width/4+offset,endx,endy-full_width/4+offset,endx+full_height/2,endy-full_width/4+offset,endx+3*full_height/4,endy-3*full_width/8+offset,endx,endy-3*full_width/8+offset,end

37、x+3*full_height/4,endy-3*full_width/8+offset,endx+full_height,endy-full_width/2+offset,endx,endy-full_width/2+offset,endx+full_height,endy-full_width/2+offset,endx+3*full_height/4,endy-5*full_width/8+offset,endx,endy-5*full_width/8+offset,endx+3*full_height/4,endy-5*full_width/8+offset,endx+full_hei

38、ght/2,endy-3*full_width/4+offset,endx,endy-3*full_width/4+offset,endx+full_height/2,endy-3*full_width/4+offset,endx+full_height/4,endy-7*full_width/8+offset,endx,endy-7*full_width/8+offset,endx+full_height/4,endy-7*full_width/8+offset,endx,endy-full_width+offset)offset-=full_width+spacing实心三角绘制示意图方法参数中加入nfullflagsdef_make_barbs(self,u,v,nfullflags,nflags,nbarbs,half_barb,empty_flag,length,pivot,sizes,fill_empty,flip):2. 实心三角个数计算def_find_tails(self,mag,rounding=True,half=2,full=4,flag=20,fullflag=50):Findhowmanyofeachofthetailpiecesisnecessary.Flagspec

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论