首页 > 解决方案 > Pyplot:将线条样式更改为箭头

问题描述

我写了这段代码,它制作了一个多线图:

import numpy as np
from matplotlib.pylab import plt

test1 = [0,4]
test2 = [0,6.7]
test3 = [0,8.8]
test4 = [0,4.4]
test5 = [0,7.6]
test6 = [0,33.5]
test7 = [0,21]
test8 = [0,17.65]


# Plotting functionality starts here
plt.figure(figsize=(16,12),dpi=500)
plt.plot(test1,label='test1',color='b',linewidth=4)
plt.plot(test2,label='test2',color='g',linewidth=4)
plt.plot(test3,label='test3',color='r',linewidth=4)
plt.plot(test4,label='test4',color='c',linewidth=4)
plt.plot(test5,label='test5',color='m',linewidth=4)
plt.plot(test6, label='test6',color='dimgray',linewidth=4)
plt.plot(test7, label='test7',color='peru',linewidth=4)
plt.plot(test8, label='test8',color='blueviolet',linewidth=4)


plt.ylabel('Rate',fontsize=14,fontweight='bold')
plt.xlabel('Year',fontsize=14,fontweight='bold')
plt.title('Growth',fontsize=14,fontweight='bold')
#plt.legend(loc='upper left',bbox_to_anchor=(1,1),fontsize=14)
plt.xticks([0,1],['Year1','Year2'],fontweight='bold')
plt.yticks(fontsize=16)
#plt.xticks([])
plt.tight_layout(pad=6.0)

我希望每行在行尾都有一个指向它的箭头。我在 SO 上看到了一堆类似的问题,说要使用 quiver 或其他方法。是否没有像 'arrow=True' 之类的简单命令添加到 'plt.plot(test1,label='test1',color='b',linewidth=4)' 之类的?如果是这样,有人可以给我举个例子吗?

(我不够强大,无法理解如何在其中实现 quiver;如果有人可以向我展示如何在这个示例中实现 quiver,那就太好了)。

标签: pythonmatplotlib

解决方案


ax.annotate()优于ax.arrow(),得到的箭头arrow()受轴纵横比和限制的影响。

import numpy as np
from matplotlib.pylab import plt




# Plotting functionality starts here
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))

ax.annotate("", xy=(1, 10), xytext=(0, 0),arrowprops=dict(arrowstyle="->"))
ax.annotate("", xy=(1, 5), xytext=(0, 0),arrowprops=dict(arrowstyle="->"))
ax.annotate("", xy=(1, 6), xytext=(0, 0),arrowprops=dict(arrowstyle="->"))

plt.xticks([0,1],['Year1','Year2'],fontweight='bold')
plt.yticks(fontsize=16)
plt.ylim(0, 35)
plt.xlim(0, 1)

在此处输入图像描述


推荐阅读