
我当前的代码绘制了以下内容,这是预期的,几乎是所希望的.
请注意,在2,2和2,3之间有一条线,如果用正确的算法代替当前代码,我认为可以删除.
上面的摘要是一个方框,装在两个方框中,振幅增加1,假设较大的方框位于其余方框的“后面”.
我编写产生上述代码的方法实际上并不是一个函数.这是一个非常丑陋的点集合,恰好类似于空心方块.
import matplotlib.path as mpathimport matplotlib.patches as mpatchesimport matplotlib.pyplot as pltfig,ax = plt.subplots()INNER_AMPliTUDE = 1.0OUTER_AMPliTUDE = 3.0Path_in = mpath.Pathpath_in_data = [ (Path_in.MOVeto,(INNER_AMPliTUDE,-INNER_AMPliTUDE)),(Path_in.liNeto,(-INNER_AMPliTUDE,INNER_AMPliTUDE)),(Path_in.CLOSEpoly,]codes,verts = zip(*path_in_data)path_in = mpath.Path(verts,codes)patch_in = mpatches.PathPatch(path_in,facecolor='g',Alpha=0.3)ax.add_patch(patch_in)x,y = zip(*path_in.vertices)line,= ax.plot(x,y,'go-')Path_out = mpath.Pathpath_out_data = [ (Path_out.MOVeto,(OUTER_AMPliTUDE,-OUTER_AMPliTUDE)),(Path_out.liNeto,(-OUTER_AMPliTUDE,OUTER_AMPliTUDE)),OUTER_AMPliTUDE-INNER_AMPliTUDE)),(-(OUTER_AMPliTUDE-INNER_AMPliTUDE),-(OUTER_AMPliTUDE-INNER_AMPliTUDE))),(OUTER_AMPliTUDE-INNER_AMPliTUDE,(Path_out.CLOSEpoly,verts = zip(*path_out_data)path_out = mpath.Path(verts,codes)patch_out = mpatches.PathPatch(path_out,facecolor='r',Alpha=0.3)ax.add_patch(patch_out)plt.Title('Square in a square in a square')ax.grID()ax.axis('equal')plt.show() 请注意我认为这是代码审查的偏离主题,因为我正在寻求扩展我的功能,而不仅仅是重写最佳实践.我觉得我完全是错误的做法.首先要做的事情.
我应该如何使用matplotlib绘制具有一定宽度的多边形,假设多边形将在外部被包围,带有相同形状且至少相同宽度并完全填充在内部?
解决方法 纯粹在matplotlib中处理多边形可能非常繁琐.幸运的是,有一个非常好的库可用于这些 *** 作: shapely.为了您的目的,parallel_offset函数是要走的路.
您感兴趣的多边形的边界由ring1,ring2和ring3定义:
import numpy as npimport matplotlib.pyplot as pltimport shapely.geometry as sgfrom descartes.patch import polygonPatch# if I understood correctly you mainly need the difference d hereINNER_AMPliTUDE = 0.1OUTER_AMPliTUDE = 0.2d = OUTER_AMPliTUDE - INNER_AMPliTUDE# fix seed,for reproducabilitynp.random.seed(11111)# a function to produce a "random" polygondef random_polygon(): nr_p = np.random.randint(7,15) angle = np.sort(np.random.rand(nr_p)*2*np.pi) dist = 0.3*np.random.rand(nr_p) + 0.5 return np.vstack((np.cos(angle)*dist,np.sin(angle)*dist)).T# your input polygonp = random_polygon()# create a shapely ring objectring1 = sg.linearRing(p)ring2 = ring1.parallel_offset(d,'right',join_style=2,mitre_limit=10.)ring3 = ring1.parallel_offset(2*d,mitre_limit=10.)# revert the third ring. This is necessary to use it to procude a holering3.coords = List(ring3.coords)[::-1]# inner and outer polygoninner_poly = sg.polygon(ring1)outer_poly = sg.polygon(ring2,[ring3])# create the figurefig,ax = plt.subplots(1)# convert them to matplotlib patches and add them to the axesax.add_patch(polygonPatch(inner_poly,facecolor=(0,1,0.4),edgecolor=(0,1),linewidth=3))ax.add_patch(polygonPatch(outer_poly,facecolor=(1,edgecolor=(1,linewidth=3))# cosmeticsax.set_aspect(1)plt.axis([-1.5,1.5,-1.5,1.5])plt.grID()plt.show()
结果:
总结以上是内存溢出为你收集整理的python – 图中的图中的图全部内容,希望文章能够帮你解决python – 图中的图中的图所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)