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

Python使用PySimpleGUI在同一坐标轴上基于多列表绘制多条折线的方法

问题解决代码实现

修改说明

  • 统一匹配三组数据的长度,避免索引越界报错
  • 为三条折线设置差异化配色:实测心率为蓝色、目标区间上限为红色、目标区间下限为绿色
  • 抽离公共X轴坐标计算逻辑,减少重复代码

完整可运行代码

import PySimpleGUI as sg
import json
import datetime

plotMin = [123]*60
plotMax = [200]*60
listBPM = [65,67,70,72,80,85,90,95,110,115,130]

BAR_WIDTH = 10
BAR_SPACING = 16
EDGE_OFFSET = 3
GRAPH_SIZE = (550,500)
DATA_SIZE = (500,200)
graph = sg.Graph(GRAPH_SIZE, (0,-30), DATA_SIZE, background_color='white',)

sg.theme('DarkAmber')

layout = [[sg.Text('心率检测图表')],
          [graph],
          [sg.Button('绘制图表')]]

window = sg.Window('心率监测', layout)

while True:
    event, values = window.Read()
    graph.Erase()
    if event is None:
        break
    # 取三组数据的最小长度避免索引越界
    max_len = min(len(listBPM), len(plotMin), len(plotMax))
    if max_len < 2:
        continue
    # 初始化上一个点的数值
    before_bpm = listBPM[0]
    before_max = plotMax[0]
    before_min = plotMin[0]
    for i in range(1, max_len):
        # 计算当前和上一个点的X坐标
        prev_x = (i-1) * BAR_SPACING + EDGE_OFFSET + BAR_WIDTH/2
        curr_x = i * BAR_SPACING + EDGE_OFFSET + BAR_WIDTH/2
        # 绘制目标区间上限红线
        graph.DrawLine((prev_x, before_max), (curr_x, plotMax[i]), color='red', width=1)
        # 绘制目标区间下限绿线
        graph.DrawLine((prev_x, before_min), (curr_x, plotMin[i]), color='green', width=1)
        # 绘制实测心率蓝线
        curr_bpm = listBPM[i]
        graph.DrawLine((prev_x, before_bpm), (curr_x, curr_bpm), color='blue', width=1)
        # 绘制实测点和数值标注
        graph.DrawPoint((curr_x, curr_bpm), size=3, color='blue')
        graph.DrawText(text=curr_bpm, location=(curr_x, curr_bpm + 10))
        # 更新上一个点的数值
        before_bpm = curr_bpm
        before_max = plotMax[i]
        before_min = plotMin[i]

window.Close()

运行说明

点击界面上的「绘制图表」按钮即可同时渲染三条折线,红色水平直线为心率上限,绿色水平直线为心率下限,蓝色折线为实测心率数据,每个实测心率点都配有数值标注。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:36:01