| 
 
	积分1965贡献 精华在线时间 小时注册时间2014-4-13最后登录1970-1-1 
 | 
 
| 
本帖最后由 柿子柿子柿子 于 2020-9-6 17:33 编辑
x
登录后查看更多精彩内容~您需要 登录 才可以下载或查看,没有帐号?立即注册 
  
 导出参考了一堆的程序后,总结出来的一小段只需要matplotlib和shapefile这两个包就可以进行白化的方法。
 =========================================================(我也不知道为什么添加代码文字会无法显示)
 
 # mask area
 shpname = r'map/City.shp'
 _shapes = shapefile.Reader(shpname, encoding = 'gb2312').shapes()
 poly_verts = []
 poly_codes = []
 for i in _shapes:
 # _flag 判断是不是闭合圈新的开始点
 _flag = 0
 for xx, yy in i.points:
 if _flag == 0:
 # 当前点是起始点时
 x0, y0 = xx, yy
 _flag = 1
 poly_verts.append((xx,yy))
 poly_codes.append(mpath.Path.MOVETO)
 else:
 # 当前点不是起始点
 if (x0, y0) == (xx, yy):
 # 当前点是结束点时
 _flag = 0
 poly_verts.append((xx,yy))
 poly_codes.append(mpath.Path.CLOSEPOLY)
 else:
 # 当前点不是结束点
 poly_verts.append((xx,yy))
 poly_codes.append(mpath.Path.LINETO)
 path = mpath.Path(poly_verts, poly_codes)
 patch = mpatches.PathPatch(path, visible = True, fc = 'none')
 del(shpname, _shapes, poly_verts, poly_codes, _flag, xx, yy)
 
 
 =========================================================
 
 这个是用了mpatches.PathPatch画多边形的思路进行的。需要改动的就是shpname来导入自己的shp文件。换言之,及时不是shp文件,直接用个Excel把边界的经纬度点都顺序列出来也得的。思路就是这么个样子。
 
 另外,只想白化不想画边界的话,mpatches.PathPatch中visible设置成False就好。
 还有就是,如果只想部分白化,但shp里区域又过多,在_shapes的时候截取需要的那部分就好。如for i in _shapes[98:105]:
 
 
 
 然后下面的是绘图和白化的部分。我不加copy.deepcopy这个(前面import copy就好,印象中默认安装有的包,没有的话就装一个),直接用ax.add_patch(patch)的时候,在循环出图到第二轮时会出错……
 
 
 =========================================================
 
 
 cs = ax.contourf(lon, lat, data, clevs, extend='max', colors = color)
 
 # mask
 _tmp = copy.deepcopy(patch)
 ax.add_patch(_tmp)
 for c in cs.collections:
 c.set_clip_path(_tmp)
 del(_tmp)
 
 =========================================================
 
 
 | 
 |