【问题标题】:why Plot Python 3 different with Matlab and even excel为什么 Plot Python 3 与 Matlab 甚至 excel 不同
【发布时间】:2021-12-13 21:18:48
【问题描述】:

我试图从 scv 文件中读取数据并绘制它们。读取过程很容易工作,但通过绘图完全错过了。 我用 MATLAB 甚至 Excel 都试过了。两者都绘制正确,但在 python 3 中我有问题。似乎是这样。 Plot Photo with python Plot Photo with MATLAB

感谢您的帮助

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 将对象 (line[0], line[1]) 作为字符串返回。您需要转换为正确的数据类型,例如ypoints.append(float(line[1]))。也可以考虑import pandas as pd; df=pd.read_csv(filename1)
  • 另外,请发帖minimal reproducible example。这段代码中有很多损坏的位。

标签: python-3.x matplotlib


【解决方案1】:

每个line 都是一个字符串的元组。因此,xpointsypoints字符串 的列表。因此,Matplotlib 将尝试将 所有 个可能的值作为刻度,这就是绘图如此混乱的原因。

您应该将line 的每个元素视为一个数字:

xpoints = []
ypoints = []
for line in reader:
    xpoints.append(float(line[0]))
    ypoints.append(float(line[1]))

或者,使用numpy.loadtxt,它会自动将数字转换为浮点或整数类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2016-09-22
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多