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

如何使用Matplotlib绘制带有两种并行颜色的单条折线

双并行色单折线实现方案

实现逻辑

放弃原方案的坐标值偏移思路,改用Matplotlib内置的路径偏移效果,沿折线法线方向做像素级固定偏移,从根源解决原方案的两个缺陷。

示例代码

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patheffects as pe

# 生成测试数据
x = np.linspace(0, 1, 100)
y = np.exp(x)

line_width = 2
parallel_offset = 1  # 单边偏移量,单位为印刷点,1点约等于1/72英寸

# 沿折线法线正方向偏移绘制绿色线
plt.plot(x, y, color='g', linewidth=line_width,
         path_effects=[pe.ParallelOffset(parallel_offset, corner_mode='round'), pe.Normal()])
# 沿折线法线负方向偏移绘制红色线
plt.plot(x, y, color='r', linewidth=line_width,
         path_effects=[pe.ParallelOffset(-parallel_offset, corner_mode='round'), pe.Normal()])

plt.show()

方案优势

  • 缩放无错位:偏移采用固定物理单位,无论画布如何放大缩小,两条线的相对间距始终保持一致,不会出现分离
  • 全角度适配:偏移方向始终沿折线的法线方向计算,折线为水平、垂直或任意倾斜角度时,都能保持并行效果,无需额外调整坐标偏移量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:24:05