Python 打印2.dat文件,字符串文件句柄错误

Python 打印2.dat文件,字符串文件句柄错误,python,matplotlib,Python,Matplotlib,您好,我正在尝试在同一绘图上绘制两个.dat文件中的数据。 当我尝试时,会收到一条错误消息。我在下面的代码中显示了它的确切来源。它与字符串或文件句柄有关。我对python非常陌生,不知道如何解决这个问题 我导入了两个.dat文件,它们都是有两列的文件。 然后我用指定的字体大小定义x、y轴的名称,然后对标题执行相同的操作。然后我尝试在一个绘图上绘制两个.dat文件 import numpy as np from matplotlib import pyplot as plt fig = plt.

您好,我正在尝试在同一绘图上绘制两个.dat文件中的数据。 当我尝试时,会收到一条错误消息。我在下面的代码中显示了它的确切来源。它与字符串或文件句柄有关。我对python非常陌生,不知道如何解决这个问题

我导入了两个.dat文件,它们都是有两列的文件。 然后我用指定的字体大小定义x、y轴的名称,然后对标题执行相同的操作。然后我尝试在一个绘图上绘制两个.dat文件

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

#unpack file data

dat_file = np.loadtxt("file1.dat", unpack=True)
dat_file2 = np.loadtxt("file2.dat", unpack=True)

plt.xlabel('$x$', fontsize = 14)
plt.ylabel('$y$', fontsize = 14)
plt.title('result..', fontsize = 14)

plot1 = plt.plotfile(*dat_file, linewidth=1.0, marker = 'o') #error message from this line
plot2 = plt.plotfile(*dat_file2, linewidth=1.0, marker = 'v') #error message from this line

plt.plotfile([plot1,plot2],['solution 1','solution 2'])

plt.show()

非常感谢您的帮助。

您必须使用
绘图功能进行绘图:

...
plot1 = plt.plot(*dat_file, linewidth=1.0, marker = 'o', label='solution 1') 
plot2 = plt.plot(*dat_file2, linewidth=1.0, marker = 'v', label='solution 2') 
ax = plt.gca()
ax.legend(loc='best')
plt.show()

plotfile
需要设置分隔符(默认为“,”)和文件名而不是数组,您必须这样写:

plot1 = plt.plotfile("file1.dat", linewidth=1.0, marker = 'o', delimiter=' ', newfig=False,  label='solution 1')
plot2 = plt.plotfile("file2.dat", linewidth=1.0, marker = 'v', delimiter=' ', newfig=False,  label='solution 2') 
plt.title("Result")
plt.xlabel('$x$', fontsize = 14)
plt.ylabel('$y$', fontsize = 14)
ax = plt.gca()
ax.legend(loc='best')
plt.show()    

newfig=False
控制是否在新图形上绘制数据。

谢谢,让我来看看所有细节!我真的很感激。如果我有问题,我会在这里发布。一切都很顺利,我可以跟随你所做的。非常感谢您的解释和帮助。