matplotlib PatchCollection绘制一个缩放过大的箭头面片

ovfsdjhp  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(116)

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

  1. import matplotlib.pyplot as plt
  2. import matplotlib as mpl
  3. fig, ax = plt.subplots()
  4. points = ax.scatter([0,1],[0,1], marker='o', s=300)
  5. arrow = mpl.patches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=20)
  6. ax.add_patch(arrow)
  7. fig.show()

看起来还可以

现在,让我们做同样的图,但使用PatchCollection

  1. import matplotlib.pyplot as plt
  2. import matplotlib as mpl
  3. fig, ax = plt.subplots()
  4. points = ax.scatter([0,1],[0,1], marker='o', s=300)
  5. arrow = mpl.patches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=20)
  6. col = mpl.collections.PatchCollection([arrow])
  7. ax.add_collection(col)
  8. fig.show()

有人能解释一下发生了什么吗?

cwtwac6a

cwtwac6a1#

FancyArrowPatch主要设计用于注解。显然缺乏与其他补丁的兼容性,因此是PatchCollection。(正如@tom在评论中指出的那样,链接到[这个问题])。
解决方法是从箭头的路径创建一个新的补丁,并将该新补丁添加到集合中。这不允许保留FancyArrowPatch的所有功能,因此最终是否完全不使用PatchCollection不是一个更好的解决方案是值得怀疑的。

  1. import matplotlib.pyplot as plt
  2. import matplotlib as mpl
  3. import matplotlib.patches as mpatches
  4. fig, ax = plt.subplots()
  5. points = ax.scatter([0,1],[0,1], marker='o', s=300)
  6. arrow1 = mpatches.FancyArrowPatch((0,0), (1,1), arrowstyle='-|>', mutation_scale=50)
  7. arrow2 = mpatches.FancyArrowPatch((.7,0), (0.1,0), arrowstyle='->', mutation_scale=30)
  8. def arrows2collection(ax, arrows,**kw):
  9. p = []
  10. for arrow in arrows:
  11. ax.add_patch(arrow)
  12. path = arrow.get_path()
  13. p.append(mpatches.PathPatch(path,**kw))
  14. arrow.remove()
  15. col = mpl.collections.PatchCollection(p,match_original=True)
  16. ax.add_collection(col)
  17. return col
  18. col = arrows2collection(ax, [arrow1,arrow2], linewidth=1)
  19. plt.show()
展开查看全部

相关问题