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

Matplotlib线条宽度增加时位置偏移问题求助

问题原因

matplotlib的plt.plot()绘制线条时,线条是居中对齐的:线条中心沿你定义的线段(xDist1)分布,而线条粗细(linewidth)会向线段两端外侧延伸。当线条较粗时,这种延伸会导致视觉上线条超出预期的x范围,甚至跑到0刻度左侧。

解决方案

推荐使用plt.fill_between()替代plt.plot(),直接填充矩形区域模拟粗线条效果——这种方式可以精确控制显示范围,完全避免偏移问题。

代码修改示例

if len(Ldist_km) == len(leftBank_filled['rev2003_LC']):
    print('plotting left')
    # 定义y方向偏移量,控制"线条"的视觉粗细,可根据你的y轴范围调整
    line_thickness = 0.1
    y_bottom = yL - line_thickness
    y_top = yL + line_thickness
    
    for Lp in range(len(leftBank_filled['rev2003_LC'])-1):
        x_start = Ldist_km[Lp]
        x_end = Ldist_km[Lp+1]
        # 填充x从x_start到x_end、y从y_bottom到y_top的区域
        plt.fill_between(
            [x_start, x_end],
            y_bottom,
            y_top,
            color=leftBank_filled['ColorFormula'][Lp],
            edgecolor=None  # 不需要额外边缘线
        )

补充方案:使用plt.hlines()

如果更习惯用线条类函数,plt.hlines()的显示逻辑更贴合需求:它的线宽是垂直于线条方向的厚度(即y方向高度),x方向严格限制在xmin到xmax之间,不会向外延伸。

代码示例:

if len(Ldist_km) == len(leftBank_filled['rev2003_LC']):
    print('plotting left')
    # linewidth控制y方向厚度,对应视觉上的线条粗细
    for Lp in range(len(leftBank_filled['rev2003_LC'])-1):
        x_start = Ldist_km[Lp]
        x_end = Ldist_km[Lp+1]
        plt.hlines(
            y=yL,
            xmin=x_start,
            xmax=x_end,
            color=leftBank_filled['ColorFormula'][Lp],
            linewidth=6  # 可根据需要调整粗细
        )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:27:40