gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:49:31 28 4
gpt4 key购买 nike

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

我正在处理的最少代码:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com