首页 > 解决方案 > 如何使用 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)   

标签: pythonmatplotlib

解决方案


推荐阅读