python - 使用 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
以进行一些投影、更改视点等。
请注意,结果高度依赖于绘制的表面。有时不会出现伪影,有时会比这更糟。
解决方案
我设法找到了问题。当包含的路径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]) )
推荐阅读
- c# - 类字段中类名的目的?
- apache-spark - spark 下推过滤器如何与 cassandra 表非分区键一起使用?
- wpf - WPF 隐藏 ItemsControl 的第一项(组合框、文本框等)
- mongodb - 如何使用 Spring Data MongoDB 搜索嵌套在数组中的对象列表?
- python - 在处理双端队列时接收 UDP 消息
- pandas - 使用 pandas 进行断言式编程
- shiro - 使用加密数据的 Apache Shiro 身份验证
- ruby-on-rails - 从多个模型中查询值
- html - 通过将数据从一个控制器传递到另一个控制器来触发预览模式
- regex - 使用 sed 从多个文件中删除多行