首页 > 解决方案 > 使用 PatchCollection 重新绘制等高线填充图

问题描述

我正在尝试使用来自原始其他等高线图的集合来显示填充等高线图。但是,我遗漏了一些东西,因为我的代码不能完全再现等高线图。

我正在处理的最小代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection, PolyCollection

x = np.arange(0, 300,1)
y = np.arange(0, 300,1)
X, Y = np.meshgrid(y, x)
Topo = np.cos(X*2*np.pi/50)*np.sin(Y*2*np.pi/200)*y

plt.figure()
ax = plt.subplot(1,2,1)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

Ncolors = 50
levels = np.linspace(np.min(Topo),np.max(Topo),Ncolors)
# h = plt.contourf(X,Y, Topo, levels = levels, cmap = cmap, vmin = 0.85*np.min(Topo), zorder = -10)
h = plt.contourf(Y, X, Topo, levels = levels)

ax = plt.subplot(1,2,2)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

i = 0
for levellines in h.collections:
    for lines in levellines.get_paths():
        plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
    i = i+1
plt.xlim([x.min(), x.max()])
plt.ylim([y.min(), y.max()])

在此处输入图像描述 您可能会问我为什么要尝试通过 Polygon 函数和路径顶点:稍后,我需要稍微更改顶点的坐标lines.vertices以进行一些投影、更改视点等。

请注意,结果高度依赖于绘制的表面。有时不会出现伪影,有时会比这更糟。

标签: pythonmatplotlib

解决方案


我设法找到了问题。当包含的路径lines不是简单路径,而是贝塞尔曲线或其他时,就会出现伪影。

因此,您需要绘制路径而不是多边形来添加包含在codes属性中的信息。

只是使用:

from matplotlib.path import Path
import matplotlib.patches as patches

接着 :

plt.gca().add_patch(patches.PathPatch( Path(lines.vertices, lines.codes) , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )

代替

 plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )

最后,您还可以使用以下方法将路径转换为多边形.to_polygons()

 plt.gca().add_collection(PatchCollection( [ Polygon( lines.to_polygons() ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )

推荐阅读