python - 使用path.cleaned删除matplotlib.path中多余的点

标签 python matplotlib data-cleaning

我正在尝试使用 Path.cleaned 来简化 matplotlib.path.Path 的实例,即我想删除对路径形状没有贡献的点(如 Path.iter_segments 的文档中所述)。 我在下面写了一个小示例,其中 [0, 0.5] 处的一个点被删除,但生成了另一个点!我还发现了一个issue on GitHub解决这个问题,特别是 this comment

之前的点是[[0, 0], [0, 0.5], [0, 1], [1, 1], [1, 0], [0, 0]],清洗后的点为[[0, 0], [0, 1], [1, 1], [1, 0], [1, 0], [0, 0]] 倒数第二点和第三点相同。

import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as mpatches
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

verts = [[0, 0], [0, 0.5], [0, 1], [1, 1], [1, 0], [0, 0]]
codes = [1, 2, 2, 2, 2, 0]  # use 79 instead of 0 for correctly drawn path border

path = Path(verts, codes)
path.should_simplify = True
cleaned_path = path.cleaned(simplify=True)

patch = mpatches.PathPatch(cleaned_path)
plt.plot(np.asarray(verts)[:, 0], np.asarray(verts)[:, 1], "rx")

ax.add_patch(patch)
plt.show()

我该如何解决这个问题?顺便说一句,我正在使用最新的 matplotlib 版本(2.1.2)。

最佳答案

查看 github 问题,我不太确定这是否可以解决您的问题以及应该在哪个版本中包含提到的修复。同时,您自己删除重复项怎么样:

new_verts = []
new_codes = []
for vert, code in cleaned_path.iter_segments():
    if not new_verts or (np.any(vert != new_verts[-1]) or code != new_codes[-1]):
        new_verts.append(vert)
        new_codes.append(code)

new_path = Path(new_verts, new_codes)

print(new_path.vertices)

输出:

[[0. 0.]
 [0. 1.]
 [1. 1.]
 [1. 0.]
 [0. 0.]]

关于python - 使用path.cleaned删除matplotlib.path中多余的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443102/

相关文章:

python - 从数据框中删除特殊字符和字母数字的简单方法

Python Pytz 美国/太平洋时区问题

python - pygame保存音频文件

python - 如何比较两个数据框,并添加两者之一没有的行和列

coldfusion - Coldfusion 9中的清洁字符串/输入

python - 从每一行中删除字符串标签

python - 如何让狮身人面像识别装饰过的 python 函数

python - 如何在 Matplotlib 中排列嵌套子图?

python - 使用 LogNorm 和 ImageGrid 时的 Matplotlib 颜色条

python - 将正态分布拟合到一维数据