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

Python3读取CSV绘图结果与MATLAB、Excel显示不一致问题求助

问题描述

读取CSV文件数据绘图时,数据读取流程无报错,但最终绘图结果完全错乱。相同数据用MATLAB、Excel绘图均可正常生成正确图表,仅Python 3环境下绘图异常。
原有实现代码如下:

filename1=fd.askopenfilename(title='open expander text data to graphic ')
reader=csv.reader(filename1)
xpoints = []
ypoints = []
for line in reader:
    xpoints.append(line[0])
    ypoints.append(line[1])
xpoints_to_graph=np.array(xpoints[])
ypoints_to_graph=np.array(ypoints[])

plt.plot(xpoints_to_graph,ypoints_to_graph)
错误原因

代码存在三处直接导致绘图异常的问题:

  • csv.reader 入参必须是已打开的文件对象,直接传入文件路径字符串时,csv.reader会逐字符遍历路径字符串解析,根本没有读取到目标CSV的实际内容
  • CSV读取到的单元格内容默认是字符串类型,未做数值转换的情况下,matplotlib会将字符串识别为离散分类值,无法按连续数值坐标渲染折线
  • np.array(xpoints[]) 属于无效语法,空方括号为非法切片写法
修正方案

修正后可正常运行的代码如下:

import csv
import numpy as np
import matplotlib.pyplot as plt
import tkinter.filedialog as fd

filename1 = fd.askopenfilename(title='open expander text data to graphic ')
xpoints = []
ypoints = []
# 上下文管理器打开文件,自动处理资源释放
with open(filename1, 'r', encoding='utf-8') as csv_file:
    reader = csv.reader(csv_file)
    # 若CSV文件包含表头行,取消下一行注释跳过表头
    # next(reader)
    for row in reader:
        # 读取单元格内容后转为浮点数值
        xpoints.append(float(row[0]))
        ypoints.append(float(row[1]))
# 转换numpy数组时移除无效空切片
xpoints_to_graph = np.array(xpoints)
ypoints_to_graph = np.array(ypoints)

plt.plot(xpoints_to_graph, ypoints_to_graph)
plt.show()

注意:如果你的CSV文件不是用逗号做分隔符,需要在初始化csv.reader时传入delimiter参数指定分隔符,比如制表符分隔的文件写为csv.reader(csv_file, delimiter='\t')。

内容的提问来源于stack exchange,提问作者s.aghajan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.22 16:15:00