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

Python数据绘图程序折线图无法显示问题排查求助

Python折线图无法显示的问题修复(读取TXT数据并绘图)

问题根源分析

  1. 数据读取逻辑错误:原代码用zip(data_names, data_values)将每个数据类型与单个值配对,丢失了后续测量数据。实际上TXT中的数据按每组6个值对应一次全类型测量排列,需将每个类型的所有测量值归类到同一列表。
  2. 绘图函数参数与逻辑错误:传入绘图函数的是单个值而非值列表,导致每个类型仅绘制孤立点,无法形成折线;同时类型名称与值的对应关系错位。

修正后的完整代码

import matplotlib.pyplot as plt
import PySimpleGUIWx as sg


# 파일 불러오기 대화상자 생성
def create_file_dialog():
    layout = [
        [sg.Text("데이터 파일 선택:")],
        [sg.Input(key="-FILE-"), sg.FileBrowse()],
        [sg.Button("데이터 그래프 생성", key="-PLOT-")]
    ]
    window = sg.Window("데이터 파일 불러오기", layout)
    return window


# 데이터 파일에서 데이터 읽기 (修正逻辑)
def read_data_from_file(file_path):
    data_dict = {}
    with open(file_path, "r") as file:
        num_types = int(file.readline().strip())
        # 读取数据类型名称并初始化空列表
        for _ in range(num_types):
            name = file.readline().strip()
            data_dict[name] = []
        # 读取所有数值
        data_values = []
        for line in file:
            stripped_line = line.strip()
            if not stripped_line:
                continue
            try:
                data_values.append(float(stripped_line))
            except ValueError:
                pass
        # 按数据类型数量分组,分配到对应类型的列表中
        num_values = len(data_values)
        num_remaining = num_values % num_types
        if num_remaining != 0:
            data_values = data_values[:-num_remaining]  # 截断多余的数值
        # 分组填充数据
        for i in range(0, len(data_values), num_types):
            group = data_values[i:i+num_types]
            for idx, name in enumerate(data_dict.keys()):
                data_dict[name].append(group[idx])
    # 转换为(类型名, 值列表)的列表格式
    return list(data_dict.items())


# 데이터 그래프 생성 (修正逻辑)
def create_plot(selected_data, selected_values):
    plt.figure(figsize=(8, 6))

    colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'brown', 'gray', 'pink', 'cyan']
    for i, (name, values) in enumerate(zip(selected_data, selected_values)):
        color = colors[i % len(colors)]
        # 保留浮点类型,无需转int(如需整数可自行添加转换)
        y_values = [val for val in values]
        x = range(len(y_values))  # X轴为测量次数索引
        plt.plot(x, y_values, color=color, label=name, marker='o')  # 添加标记点增强可读性

    plt.xlabel("측정 횟수")
    plt.ylabel("데이터 값")
    plt.title("데이터 그래프")
    plt.legend()
    plt.grid(True)
    plt.show()


# GUI 실행 (修正数据处理逻辑)
def run_gui():
    window = create_file_dialog()
    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == "-PLOT-":
            file_path = values["-FILE-"]
            if not file_path:
                sg.popup("파일을 선택하세요.", title="오류")
                continue

            try:
                data = read_data_from_file(file_path)
            except Exception as e:
                sg.popup(f"파일 열기 오류: {e}", title="오류")
                continue

            data_types = [data_type for data_type, _ in data]
            num_types = len(data_types)

            if num_types > 10:
                sg.popup("데이터 종류의 개수는 10을 넘을 수 없습니다.", title="오류")
                continue

            layout = [[sg.Checkbox(data_type, key=data_type, default=True)] for data_type in data_types]
            layout.append([sg.Button("그래프 생성", key="-CREATE_PLOT-")])

            data_window = sg.Window("데이터 선택", layout)

            while True:
                data_event, data_values = data_window.read()

                if data_event == sg.WINDOW_CLOSED:
                    break
                elif data_event == "-CREATE_PLOT-":
                    selected_data = [data_type for data_type, selected in data_values.items() if selected]
                    # 获取选中类型对应的数值列表
                    selected_values = [value_list for data_type, value_list in data if data_type in selected_data]
                    create_plot(selected_data, selected_values)

            data_window.close()

    window.close()


if __name__ == "__main__":
    run_gui()

关键修改说明

  1. 数据读取函数

    • 用字典存储每个类型对应的所有值列表,避免数据丢失
    • 将数值按数据类型数量分组,依次填充到对应类型的列表中
    • 跳过空行,增强代码鲁棒性
  2. 绘图函数

    • 修改参数接收逻辑,直接配对选中的类型名称与值列表
    • 保留原始浮点数值(原代码转int会丢失精度),添加标记点使折线更直观
    • X轴改为测量次数索引,符合数据逻辑
  3. GUI逻辑

    • 修正选中值的获取方式,确保传入绘图函数的是每个类型的完整值列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:17:47