我想在以箭头结尾的特定数据坐标处向绘图添加 axvline
(并选择终止于绘图顶部的向上箭头或终止于绘图底部的向下箭头,或两者均终止)。
例如
fig, ax = plt.subplots()
ax.plot([1,2,3])
ax.axvline(1.5, arrow_head=[True,False])
会给出一条垂直线,底部有一个箭头,但顶部没有(即向下箭头)。
我看不到在 axvline
中直接执行此操作的方法,但我可以使用 ax.arrow()
和混合转换完成大部分操作(x 的数据坐标和 y 的轴坐标):
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
fig, ax = plt.subplots()
ax.plot([1,2,3],[1,4,9])
mytrans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
ax.arrow(2.5,0,0,1,transform=mytrans,head_width=0.1,length_includes_head=True)
我的问题:
1) 有没有更简单/更清洁的方法来做到这一点?
2) 你会如何用这种方式制作双箭头?
最佳答案
我只是无意中发现了同样的问题,并且认为仍然没有直接的方法可以使用 ax.axvline()
或 ax.arrow()
来做到这一点。
作为启用双端箭头(以及更多)的解决方法,我使用了
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
x = 2.5
y1, y2 = ax.get_ybound()
myArrow = FancyArrowPatch(posA=(x, y1), posB=(x, y2), arrowstyle='<|-|>', color='0.5',
mutation_scale=20, shrinkA=0, shrinkB=0)
ax.add_artist(myArrow)
plt.show()
给出以下输出:
https://stackoverflow.com/questions/48125753/