You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib折线图数据标签重叠:如何实现标签上下排列?

折线图数据标签重叠问题解决方案

问题场景

你需要在折线图中展示3种产品每季度的消费相对变化,但当前数据标签重叠,导致图表可读性差。尝试手动固定标签位置后未达预期效果,原代码如下:

for i, j in products['CATEGORY'].items():     
    ax[1].annotate(
        "{:.0f}%".format(j),                    
        xy=(i, j),                    
        xytext=(-50, 15),                    
        textcoords='offset points',                    
        fontsize=20,                    
        color=annot_colors[2])

对应的图表:
数据标签重叠的折线图


解决方法

方法1:为不同产品设置差异化偏移量

针对3种产品,给每种产品的标签分配不同的垂直偏移值,让标签上下错开排列:

# 为3种产品分别设置不同的垂直偏移
product_offsets = [15, 5, -5]
# 对应每种产品的颜色
product_colors = annot_colors[:3]

# 按产品分类遍历数据
for idx, (category, data) in enumerate(products.groupby('CATEGORY')):
    for x, y in data.items():
        ax[1].annotate(
            "{:.0f}%".format(y),                    
            xy=(x, y),                    
            xytext=(-50, product_offsets[idx]),                    
            textcoords='offset points',                    
            fontsize=20,                    
            color=product_colors[idx])

方法2:动态计算偏移量(适配数据波动)

如果产品数据波动大,固定偏移可能仍有重叠,可以根据相邻点的位置动态调整标签偏移:

prev_y = None
offset_y = 15

for i, j in products['CATEGORY'].items():
    # 如果当前点和上一个点距离过近,切换偏移方向
    if prev_y is not None and abs(j - prev_y) < 10:
        offset_y = -5 if offset_y == 15 else 15
    
    ax[1].annotate(
        "{:.0f}%".format(j),                    
        xy=(i, j),                    
        xytext=(-50, offset_y),                    
        textcoords='offset points',                    
        fontsize=20,                    
        color=annot_colors[2])
    
    prev_y = j

方法3:用第三方库自动调整标签

使用adjustText库自动识别并避免标签重叠,先安装库:pip install adjusttext,再运行以下代码:

from adjustText import adjust_text

texts = []
# 先创建所有标签对象
for i, j in products['CATEGORY'].items():
    text = ax[1].annotate(
        "{:.0f}%".format(j),                    
        xy=(i, j),                    
        fontsize=20,                    
        color=annot_colors[2])
    texts.append(text)

# 自动调整标签位置,可选添加箭头连接标签和数据点
adjust_text(texts, arrowprops=dict(arrowstyle="-", color='gray'))

内容的提问来源于stack exchange,提问作者Mariana Yakymenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:08:14