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

Matplotlib电流测量曲线绘制异常求助:Y轴格式化修正

电流曲线绘制问题修正方案

问题描述

我需要基于测量数据绘制一条电流曲线,曲线起始值为0.280A(即280mA),随后下降至接近0,但当前曲线显示效果不符合预期。以下是我使用Matplotlib、Pandas等库编写的Python代码,恳请协助修正曲线显示及Y轴格式化问题:

import matplotlib.pyplot as plt
import csv
import numpy as np
import pandas as pd

Current = 280#input("Ladesstrom in mA: 
")

x = []
y = []

with open('0C2.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=';')
    for row in lines:
        x.append(row[0])
        y.append(row[2])
        
liste = pd.read_csv('0C2.csv', sep=";")
Zeilen = len(liste)

letzte = pd.read_csv('0C2.csv',usecols=[2],skiprows=Zeilen-1, sep=";")      #letzte Zeile und Spalte 1 auslesen und in "letzte" Speichern
erste = pd.read_csv('0C2.csv',usecols=[2],nrows=1, sep=";")                 #Zeile 1 und Spalte 1 auslesen und in "erste" Speichern

StepsTime=(Zeilen)/5.005
StepsCurrent=(float(Current)/float(5.05))

print(int(Current))

plt.plot(x, y, color = 'g', marker = ',')

plt.xlabel('Time')
plt.ylabel('Current in A')
plt.title("Strommessung 0,2C")
plt.xlim(0, Zeilen)
plt.xticks(np.arange(0, Zeilen, step=StepsTime))
plt.ylim(0, Current)
plt.yticks(np.arange(0, int(Current), step=StepsCurrent))
plt.savefig('books_read.png', dpi=800)
plt.show()

问题分析

  1. 数据类型错误:直接读取CSV字符串存入列表,Matplotlib会将其视为分类数据,导致曲线显示异常。
  2. 单位不匹配:Current设为280(mA),但Y轴标注为“Current in A”,刻度范围和单位完全不匹配。
  3. 重复读取CSV:多次调用pd.read_csv造成资源浪费,且逻辑冗余。
  4. X轴范围不合理:用行数作为X轴上限,和实际时间数据不对应。

修正后的代码

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 电流设置(单位:mA,后续转换为A)
current_mA = 280  # input("Ladesstrom in mA: ")

# 一次性读取CSV数据,避免重复IO操作
df = pd.read_csv('0C2.csv', sep=';')

# 将时间列和电流列转换为数值类型,处理可能的无效值
x = pd.to_numeric(df.iloc[:, 0], errors='coerce')
y = pd.to_numeric(df.iloc[:, 2], errors='coerce')

# 过滤掉无效的NaN数据
valid_data = ~x.isna() & ~y.isna()
x = x[valid_data]
y = y[valid_data]

zeilen = len(df)

# 计算刻度步长:Y轴转换为A单位,匹配标注
steps_time = zeilen / 5.005
steps_current = (current_mA / 1000) / 5.05  # 转换为A

plt.plot(x, y, color='g', marker=',')

plt.xlabel('Time')
plt.ylabel('Current in A')
plt.title("Strommessung 0,2C")

# 基于实际时间数据设置X轴范围,也可保留原逻辑用0到zeilen
plt.xlim(x.min(), x.max())
plt.xticks(np.arange(x.min(), x.max(), step=steps_time))

# Y轴范围设为0到0.28A(对应280mA),确保和数据匹配
plt.ylim(0, current_mA / 1000)
plt.yticks(np.arange(0, current_mA / 1000 + steps_current, step=steps_current))

plt.savefig('books_read.png', dpi=800)
plt.show()

关键修改说明

  • 统一数据类型:将读取的字符串转换为数值类型,确保Matplotlib绘制连续曲线。
  • 单位统一:把mA转换为A,和Y轴标注一致,修正刻度范围。
  • 优化IO操作:用Pandas一次性读取数据,简化逻辑并提升效率。
  • 处理无效数据:过滤CSV中的非数值内容,避免绘图报错。
  • 贴合真实数据:基于实际时间值设置X轴范围,让曲线显示更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:45:46