具有相同头部长度的 Python 注释箭头 [英] Python annotation arrows with same headlength

查看:24
本文介绍了具有相同头部长度的 Python 注释箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 matplotlib 创建带箭头的注释.

I'm using matplotlib to create annotations with arrows.

from matplotlib import pyplot as plt
plt.figure()
plt.annotate('Text1', xy=(1, 0), xytext=(1, 1), arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10))
plt.annotate('Text2', xy=(3, 0), xytext=(3, 3), arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10))
plt.annotate('Text3', xy=(6, 0), xytext=(6, 6), arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10))
plt.annotate('Text4', xy=(9, 0), xytext=(9, 9), arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10))
plt.xlim((0, 10))
plt.ylim(0, 10)
plt.show()

可以看出,箭头的长度受线长的影响,并且在箭头之间有所不同.

As can be seen, the length of the arrow heads is affected by the line-length and varies between the arrows.

我正在寻找一种方法来创建具有不同线长但相同箭头长度的箭头.尽管注释手册页上列出了许多选项,但我无法产生所需的结果.

I'm looking for a way to create arrows with different line-lengths but equal arrow-headlengths. Although many options are listed on the annotations manual page, i was not able to produce the desired result.

作为替代方法,我尝试使用 plt.arrow 单独绘制箭头.在那种情况下,箭头看起来像预期的那样,但是当使用透明度时,额外的线条变得可见.

As an alternative approach i tried to plot the arrows seperatedely using plt.arrow. In that case the arrow heads looked as desired, but when using transparency, additional lines became visible.

最好的问候,zinjaai

Best regards, zinjaai

推荐答案

arrowprops 中你不能指定头部的长度,但是 frac 论证指定头部的长度作为箭头长度的分数.由于您知道 xyxytext,您可以计算所需头部长度的必要分数.

In the arrowprops you can't specify the length of the head, but the frac arguement specifies the length of the head as a fraction the arrow length. Since you know xy and xytext you can compute the necessary fraction for a desired headlength.

对于您提供的示例(头部长度为 0.5),我没有很快完成.

I've don't it quickly for the example you provided (with an head length of 0.5).

from matplotlib import pyplot as plt
plt.figure()
plt.annotate('Text1', xy=(1, 0), xytext=(1, 1), 
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/1))
plt.annotate('Text2', xy=(3, 0), xytext=(3, 3), 
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/3))
plt.annotate('Text3', xy=(6, 0), xytext=(6, 6), 
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/6))
plt.annotate('Text4', xy=(9, 0), xytext=(9, 9), 
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/9))
plt.xlim((0, 10))
plt.ylim(0, 10)
plt.show()

结果:

您可以将其包装在一个函数中,该函数计算箭头的长度(给定 xyxytext),然后将其传递给 plt.annotate.

You could wrap this in a function, which computes the length of the arrow (given xy and xytext) and then passes that on to plt.annotate.

这篇关于具有相同头部长度的 Python 注释箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆