matplotlib简单和两个头箭头

use*_*133 7 matplotlib

我想制作一个简单的箭头和一个双头箭头.我使用以下方法制作一个简单的箭头,但我怀疑这是最简单的方法:

import matplotlib.pyplot as plt
arr_width = .009   #  I don't know what unit it is here.
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(range(10))
ax1.arrow(1, 1, 0, .5, width = arr_width, head_width = 3 * arr_width, 
    head_length = 9 * arr_width)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我找不到如何用这种方法制作两个头箭.

Ffi*_*ydd 16

您可以使用annotate带有空白文本注释的方法创建双头箭头,并将arrowpropsdict 设置为包括arrowstyle='<->'如下所示:

import matplotlib.pyplot as plt

plt.annotate(s='', xy=(1,1), xytext=(0,0), arrowprops=dict(arrowstyle='<->'))

plt.show()
Run Code Online (Sandbox Code Playgroud)

示例图

  • 该解决方案提供略微短于所需的箭头.而且,使用arrowstyle ='< - >'意味着不能在注释中使用shrink = 0.0.因此,我认为这个问题仍然存在. (2认同)
  • @newling您可以使用`plt.annotate(s ='',xy = {1,1),xytext = {0,0),arrowprops = dict(arrowstyle ='&lt;-&gt;',rinkaA = 0,rinkleB = 0 ))`代替 (2认同)
  • 在 matplotlib==3.0.0 上,我不得不将 `s=''` 更改为 `text=''`。 (2认同)

a_g*_*est 6

您可以用来matplotlib.patches.FancyArrowPatch绘制双头箭头。该类允许指定arrowstyle

import matplotlib.patches as patches

p1 = patches.FancyArrowPatch((0, 0), (1, 1), arrowstyle='<->', mutation_scale=20)
p2 = patches.FancyArrowPatch((1, 0), (0, 1), arrowstyle='<|-|>', mutation_scale=20)
Run Code Online (Sandbox Code Playgroud)

这会产生以下箭头:

箭头

  • 这是“plt.annotate”的后端顺便说一句:https://github.com/matplotlib/matplotlib/blob/v3.3.2/lib/matplotlib/text.py#L1739,但感觉更干净,因为没有虚拟空消息“s=” ''`。我对此只有一个问题(和`plt.annotate`):增加`linewidth`使指针头变圆:/sf/ask/4518182931/ Between-花式箭头补丁a/64545471#64545471 (3认同)
  • 要将“FancyArrowPatch”添加到特定轴,请使用“ax.add_patch(p1)”。还可以考虑使用“shrinkA”和“shrinkB”来避免指定坐标的偏移 (3认同)

Utk*_*tku 5

您可以通过绘制两个plt.arrow重叠的箭头来创建双头箭头。下面的代码有助于做到这一点。

import matplotlib.pyplot as plt

plt.figure(figsize=(12,6))

# red arrow
plt.arrow(0.15, 0.5, 0.75, 0, head_width=0.05, head_length=0.03, linewidth=4, color='r', length_includes_head=True)

# green arrow
plt.arrow(0.85, 0.5, -0.70, 0, head_width=0.05, head_length=0.03, linewidth=4, color='g', length_includes_head=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

双头箭头

您可以看到首先绘制红色箭头,然后绘制绿色箭头。当您提供正确的坐标时,它看起来像一个双头。