如何使用形状怪异的数组绘制数据?



出于某种原因我不明白,我用作 y 值的数组不是(4500,)形状的,而是(1125,)每行有 4 个值。我不知道如何让它工作。

这是我到目前为止尝试过的:

import matplotlib.pyplot as plt
import numpy as np

wl = np.array(range(4500,9000))
der = np.empty(4500,)
with open('der.txt') as fin:
lines = fin.readlines()
for line in lines:
np.append(der, line)

# plotting
# --------
x = wl
y = der
plt.plot(x,y)
plt.show()

.txt文件如下所示:

[1.48088146e-38 1.59775424e-38 1.59922651e-38 1.60070013e-38
1.60217510e-38 1.60365144e-38 1.49186765e-38 1.65874635e-38
1.66096308e-38 1.66203429e-38 1.66310619e-38 1.66425542e-38

继续1125行。

我对任何想法都很有帮助,因为我基本上是一个编码方面的菜鸟。提前感谢!

您读错了文件。您的文件每行包含 4 个数字,因此当您阅读它时,您需要将它们拆分为单独的数字。

假设文件中的数字用逗号分隔,您可以执行以下操作:

# read the file, split each line
with open('der.txt', 'r') as fin:
lines = fin.read().split("n")
# get rid of empty lines and split each number, but still a nested list
# here assumes the delimiter is comma, if it's something else, just change
# it accordingly
lines = [l.split(",") for l in lines if l]
# flatten the list in to a single list
der = [float(item) for sublist in lines for item in sublist]

如果你想使用numpy,你可以做:

# read matrix
from numpy import genfromtxt
der_matrix = genfromtxt('der.txt', delimiter=',')
# conver to a long array
der = my_data.flatten()

np.append涉及数组串联,这违背了将固定大小的数组der的目的。我猜每行der都有 4 个值,这就是为什么当你做np.append(der, line)时你只有 1125 行。 尝试:

index = 0
with open('der.txt') as fin:
lines = fin.readlines()
for val in line.split():
der[index] = val
index += 1

最新更新