【问题标题】:Matplotlib Custom Marker PathMatplotlib 自定义标记路径
【发布时间】:2018-04-12 08:02:21
【问题描述】:

我正在尝试使用此处记录的 Path 实例在 Matplotlib 中创建自定义标记: https://matplotlib.org/api/markers_api.html#module-matplotlib.markers

import matplotlib.pyplot as plt
import matplotlib as mpl

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]

custommarker = mpl.path.Path([[0,0],[1,1],[1,0]],[1,2,2])
plt.plot(1.5,0,marker=custommarker)

plt.plot(x, y, 'ro')
plt.subplots_adjust(bottom=0.15)
plt.show()

当我运行代码时出现错误:

TypeError: 'Path' object does not support indexing

在 mpl 1.3.x 中这是有效的,但从 mpl 2.x.x 开始出现此错误。 谁能帮我? 非常感谢。

【问题讨论】:

  • 我想你在 matplotlib 中发现了一个错误。但是,出于所有实际目的,可能有一个简单的解决方法。您是要绘制实心三角形还是倾斜的 lambda (Λ)?
  • 你用的是哪个python版本?
  • 我正在使用 python 3.6.4 mit mal 2.2.2。

标签: python matplotlib marker


【解决方案1】:

从您的代码生成的完整错误消息中,可以看出错误在实际的markers.py 函数中的set_marker 函数中。正如ImportanceOfBeingErnest in the comments 所指出的,这实际上是一个已经修复但仍未发布的错误(截至 2018 年 12 月 4 日),这可以在 markers.py 的当前主版本中看到。

引发错误的代码如下:

if (isinstance(marker, np.ndarray) and marker.ndim == 2 and
        marker.shape[1] == 2):
    self._marker_function = self._set_vertices
elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
        marker[1] in (0, 1, 2, 3)):
    self._marker_function = self._set_tuple_marker

直到某个elif 之后,才会执行对isinstance(marker,Path) 的检查。

一种解决方法是触发第一个if,以避免最终执行marker[1]。此条件检查尺寸与路径对象的顶点一致的 numpy 数组,而不是传递 custommarker,而是传递其顶点:

plt.plot(1.5,0,marker=custommarker.vertices)

另一种选择是避免第二个if 使用不同的标记长度,因为只有len(marker) in (2,3) 会出错:

custommarker = mpl.path.Path([(0,0),(1,1),(1,0),(1,0)],[1,2,2,79]) # Or a 0 as final code if instead o closing the line should stop there.

两种解决方法都给出了相同的结果。

【讨论】:

  • 你指的是当前的 master 分支,这里已经修复了这个 bug。在以前的版本中,检查marker[1] in (0, 1, 2, 3) 的行检查isinstance(marker,Path) 之前。因此出现错误。
  • 这已在当前主服务器上修复(请参阅this PR)。它还没有发布任何版本。
  • @ImportanceOfBeingErnest 谢谢!我已经编辑了答案
  • 感谢您的回答。如果它是一个已知的错误并且需要修复,我可以在 python 环境中使用旧的 mpl 版本(1.3.x)。我不明白我做错了什么。显然我不是。感谢您的澄清。
猜你喜欢
  • 2022-01-08
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2016-06-10
  • 2013-04-24
相关资源
最近更新 更多