使用PatchCollection重新绘制等高线填充图

2024-06-28 15:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图显示一个填充等高线图使用收集来从一个原始的其他等高线图。但是,我遗漏了一些东西,因为我的代码并没有准确地再现等高线图

我正在处理的最小代码:

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 你可能会问我为什么要传递多边形函数和路径顶点:稍后,我需要改变一点顶点的坐标来做一些投影,改变视点等等

请注意,结果高度依赖于绘制的曲面。。有时没有人工制品出现,有时比这更糟


Tags: importfalsegetmatplotlibnppltaxmin
1条回答
网友
1楼 · 发布于 2024-06-28 15:35:42

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

相关问题 更多 >