python - 如何使用 matplotlib 剪辑形状文件内的轮廓?
问题描述
我正在做一个内核密度图,但我的轮廓延伸到水域。我没有太多的编码经验,但我使用了一个形状文件来绘制我的“底图”。但是,我不确定如何从我的形状文件创建剪辑路径,以便将轮廓切割到国家的边缘。对此问题的任何指导将不胜感激。
我决定使用我的 shapefile 的外部边界创建一个剪辑路径。但是,当我将 set_clip_path 函数应用于我的轮廓集合时,多边形边界的内部被剪裁了。这是我使用的代码的要点。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import shapefile as shp
lon_lat_box = (-61.979370, -60.444031, 9.974261, 11.375031)
fig = plt.figure(figsize=(15,15))
ax1 = fig.add_subplot(1,1,1)
Path = mpath.Path
#read shape file
sfile = shp.Reader("./tto_adm0/TTO_adm0.shp")
#make clip path
for shape_rec in sfile.shapeRecords():
vertices = []
codes = []
pts = shape_rec.shape.points
prt = list(shape_rec.shape.parts) + [len(pts)]
for i in range(len(prt) - 1):
for j in range(prt[i], prt[i+1]):
vertices.append((pts[j][0], pts[j][1]))
codes += [Path.MOVETO]
codes += [Path.LINETO] * (prt[i+1] - prt[i] -2)
codes += [Path.CLOSEPOLY]
clip = mpath.Path(vertices, codes)
clip = mpatches.PathPatch(clip, facecolor = 'white')
#plot
ax1.add_patch(clip)
plt.xlim(lon_lat_box[0],lon_lat_box[1])
plt.ylim(lon_lat_box[2],lon_lat_box[3])
plot_map(shape_ex)
ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
contour = ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
C = plt.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
plt.colorbar(C)
for c in contour.collections:
c.set_clip_path(clip)
fig.savefig(pdf_name)
fig.show()
更新:我意识到“ax1.add_patch(clip)”行只是掩盖了国家边界内的所有轮廓填充,因为我将面部颜色设置为白色。这意味着轮廓仍然没有被我创建的补丁剪裁,我不知道为什么。
如果我删除了“ax1.add_patch(clip)”行,结果如下所示
更新 2:根据 ImportanceOfBeingErnest 的建议,我能够解决我的问题并获得所需的输出 对我的代码进行了以下调整:
contour = ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
plt.colorbar(contour)
for c in contour.collections:
c.set_clip_path(clip)
解决方案
推荐阅读
- python - ODBC SQL Server 驱动程序 - 连接正忙于处理另一个 hstmt (0) (SQLExecDirectW) 的结果
- opengl - OpenGL 固定管道渲染颜色 GL_FLOAT 不够精确
- django - 如何使用 Django rest api 更新(放置/发布请求)相关字段?
- java - Proguard 无法通过 maven 插件混淆 jar
- php - ksor PHP和排序VB.Net之间相同结果的代码比较
- javascript - 展开和折叠手风琴时,图标不会相应地切换
- python-3.x - 如何读取多个文件然后连接:我具有检查文件是否存在并读取是否存在的功能,连接时面临问题
- node.js - yaml.scanner.ScannerError:“./docker-compose.yml”第 15 行第 14 列中不允许映射值
- angular - 选择 DropDown 值,然后使用 Angular 6 导航到页面
- python - 有什么方法可以操作(添加、删除)某些键并将所有值分组到一个键下?