如何在matplotlib中获得一个开放和缩放的箭头

时间:2017-04-12 20:07:16

标签: python matplotlib seaborn

在Seaborn barplot中,我想用箭头注释一个列。现在,虽然我看到这看起来有点挑剔,但我真的很喜欢这两个

  1. 开头(即,不是一个封闭的三角形作为头部,而是两条开放的线条)和
  2. 当我调整图形大小时,
  3. 缩放
  4. 我找到了两种添加箭头的matplotlib方法(arrowannotate方法),但每种方法似乎缺少其中一种功能。这段代码并排绘制:

    import seaborn as sns
    
    sns.plt.subplot(121)
    ax = sns.barplot(("x", "y", "z"), (1, 4, 7))
    # head is not open
    ax.arrow(0, 5, 0., -3.5, lw=1, fill=False,
             head_length=.5, head_width=.2,
             length_includes_head=True)
    
    sns.plt.subplot(122)
    ax = sns.barplot(("x", "y", "z"), (1, 4, 7))
    # head does not scale with figure
    ax.annotate("", xytext=(0, 5), xy=(0, 1.5),
                arrowprops=dict(arrowstyle="->, head_length = 2, head_width = .5", lw=1))
    
    sns.plt.show()
    

    左箭头的头部是关闭的(丑陋),但是当我调整图形大小时它会很好地缩放(因为头部大小是数据单位,我假设)。右箭头很好并且打开,但无论图形大小如何,它始终保持相同的像素大小。所以当数字很小时,右箭头看起来比较大:

    Right arrow head too big

    当我把数字做得更大时,右箭头变得 - 相对 - 更小,而左箭头变得更好:

    Right arrow head too small

    那么,有没有办法让一个开放的缩放箭头?

1 个答案:

答案 0 :(得分:4)

关键是使用overhang参数并将其设置为1或接近它的位置。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4,4))

v = [-0.2, 0, .2, .4, .6, .8, 1]
for i, overhang in enumerate(v):
    ax.arrow(.1,overhang,.6,0, width=0.001, color="k", 
             head_width=0.1, head_length=0.15, overhang=overhang)

ax.set_yticks(v)
ax.set_xticks([])
ax.set_ylabel("overhang")
ax.set_ylim(-0.3,1.1)
plt.tight_layout()
plt.show()

enter image description here