python - 为 matplotlib 注释添加标签到图例
问题描述
我正在“注释”许多特定颜色的箭头以将数据添加到图表(发生事件的位置)。(示例代码)。有没有办法将它添加到图例中?一个答案可能是手动添加它们,如下面的代码所示,但我想这始终是最后的手段。什么是“正确”的做法?(在图例中也有一个小箭头标记的奖励)
这是一个例子,但实际上,这个例子是为了方便使用,问题是如何添加标签line.axes.annotate
这是一个与链接中的代码几乎相同的代码:A function to add arrows to
def add_arrow(line, position=None, direction='right', size=15, color=None, length=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
length: the number of points in the graph the arrow will consider, leave None for automatic choice
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if not length:
length = max(1, len(xdata) // 1500)
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + length
else:
end_ind = start_ind - length
if end_ind == len(xdata):
print("skipped arrow, arrow should appear after the line")
else:
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(
arrowstyle="Fancy,head_width=" + str(size / 150), color=color),
size=size
)
使用它的函数
def add_arrows(line, xs, direction='right', size=15, color=None, name=None):
if name:
if color is None:
color = line.get_color()
patch = mpatches.Patch(color=color, label=name, marker="->")
plt.legend(handles=[patch])
for x in xs:
add_arrow(line, x, color=color)
什么线的例子
x,y = [i for i in range(10000)], [i for i in range(10000)]
line = plt.plot(x, y, label="class days")[0]
add_arrows(line, (x,y))
plt.show()
解决方案
推荐阅读
- linux - 如何重命名/移动文件并保留文件名的中间?我正在使用通配符来查找文件
- java - Import JavaFX 11 Maven project to Eclipse
- cplex - Docplex 与 CPLEX Python API
- java - 在预期之前执行的代码块代替布尔值
- sql - VS 2017 数据库项目,缺少触发器
- arrays - Angular:引导模式值第一次没有绑定
- sql - SQL 更新存储在 ntext 列中的 XML 值
- bash - Basename 在 bash 中删除我的“查找”列表的第二个文件
- php - 动态调用类中的方法
- flutter - 尝试从 youtube-search-tutorial 实现 BLoC 时出现颤振错误