【问题标题】:matplotlib PatchCollection draws an over-scaled arrow patchmatplotlib PatchCollection 绘制一个过度缩放的箭头补丁
【发布时间】:2017-11-21 08:35:22
【问题描述】:

让我们使用 FancyArrowPatch 在两个散点之间画一个箭头:

import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax  = plt.subplots()

points = ax.scatter([0,1],[0,1], marker='o', s=300)
arrow = mpl.patches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=20)
ax.add_patch(arrow)

fig.show()

看起来不错

现在,让我们使用 PatchCollection 进行相同的绘图

import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax  = plt.subplots()

points = ax.scatter([0,1],[0,1], marker='o', s=300)
arrow = mpl.patches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=20)
col = mpl.collections.PatchCollection([arrow])
ax.add_collection(col)
fig.show()

有人可以澄清发生了什么吗?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

FancyArrowPatch 主要设计用于注释。与其他补丁明显缺乏兼容性,因此与 PatchCollection 不兼容。 (正如@tom 在 cmets 中指出的那样,链接到 [this issue])。

一种解决方法可能是从箭头的路径创建一个新补丁并将该新补丁添加到集合中。这不允许保留 FancyArrowPatch 的所有功能,因此最终是否完全不使用 PatchCollection 是否不是更好的解决方案值得怀疑。

import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches

fig, ax  = plt.subplots()

points = ax.scatter([0,1],[0,1], marker='o', s=300)
arrow1 = mpatches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=50)
arrow2 = mpatches.FancyArrowPatch((.7,0), (0.1,0), arrowstyle='->', mutation_scale=30)

def arrows2collection(ax, arrows,**kw):
    p = []
    for arrow in arrows:
        ax.add_patch(arrow)
        path = arrow.get_path()
        p.append(mpatches.PathPatch(path,**kw))
        arrow.remove()
    col = mpl.collections.PatchCollection(p,match_original=True)
    ax.add_collection(col)
    return col


col = arrows2collection(ax, [arrow1,arrow2], linewidth=1)


plt.show()

【讨论】:

  • +1 表示聪明的破解,尽管@tom 评论回答了这个问题。在修复错误之前,寻求的解决方案(使用FancyArrowPatch)是不可能的。
猜你喜欢
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多