python - 使用 PatchCollection 重新绘制轮廓填充图

标签 python matplotlib

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

我正在处理的最少代码:

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()])

enter image description here 正如您可能会问为什么我要尝试通过 Polygon 函数和路径顶点:稍后,我需要稍微更改顶点的坐标 lines.vertices 来进行一些投影,改变视角等..

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

最佳答案

我设法找到了问题所在。当 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]) )

关于python - 使用 PatchCollection 重新绘制轮廓填充图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363589/

相关文章:

python - 根据时间函数绘制图像 rgb 值

python - 使用pyplot绘制直方图

python - curve_fit 不能正常使用 4 个参数

python - 从Python函数内部访问全局变量

python - scipy.optimize.curve_fit 引发 RuntimeWarning

python - Matplotlib:在注释上方渲染补丁

python - 如何在一个 django 模板页面中显示多个 matplotlib 图

python - 如何找到一个包含特定字符串和最大数字的对象?

python - 从元组生成二维 bool 数组

Python 正则表达式单元测试