如何在Seaborn Lineplot中为单条折线添加图内标注而非图例
在Seaborn折线图内直接显示折线标签
方法1:手动添加文本标注
通过获取折线的终点坐标,直接在图表内对应位置添加标签,同时可移除原有图例:
import matplotlib.pyplot as plt import seaborn as sns # 绘制折线图并获取Axes对象 plt.figure(figsize=(10,8)) ax = sns.lineplot(x="Minutes", y="Hours", data=df1, hue="Product") # 提取所有折线及其对应标签 lines = ax.get_lines() labels = [line.get_label() for line in lines] # 遍历折线(跳过默认的无图例标签) for line, label in zip(lines[1:], labels[1:]): # 获取折线最后一个数据点的坐标 x_last = line.get_xdata()[-1] y_last = line.get_ydata()[-1] # 在终点右侧添加标签,微调偏移量避免遮挡折线 ax.text(x_last * 1.01, y_last, label, va='center') # 移除原有图例(不需要可删除此行) ax.legend().remove() plt.show()
方法2:用adjustText自动避免标签重叠
如果标签数量多容易重叠,可借助adjustText库自动调整标签位置,需先安装:pip install adjustText
import matplotlib.pyplot as plt import seaborn as sns from adjustText import adjust_text plt.figure(figsize=(10,8)) ax = sns.lineplot(x="Minutes", y="Hours", data=df1, hue="Product") lines = ax.get_lines() labels = [line.get_label() for line in lines] text_list = [] for line, label in zip(lines[1:], labels[1:]): x_last = line.get_xdata()[-1] y_last = line.get_ydata()[-1] text = ax.text(x_last * 1.01, y_last, label, va='center') text_list.append(text) # 自动调整标签位置,解决重叠问题 adjust_text(text_list) ax.legend().remove() plt.show()
额外说明
- 偏移量
x_last * 1.01可根据图表x轴类型调整,比如x轴是整数刻度时,可用x_last + 2这类固定值偏移 - 若不想用终点,也可选择折线的最高点、中点等位置,只需修改
x_last和y_last的取值逻辑(比如y_last = max(line.get_ydata())) - 保留原有图例的话,删除
ax.legend().remove()即可
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

