在这段代码中,我不想在代码端写入数据。如何从sample.txt
读取数据。例如,我删除了代码上的year
,unemployment
,deficit
数据集,并添加了txt文件。但我无法从txt文件中获取数据。
尝试了一些示例代码(未使用):
year=open('sample.txt','r').read()
unemployment=open('sample.txt','r').read()
deficit=open('sample.txt','r').read()
代码:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import matplotlib.dates as mdates
year = [1, 2, 3, 4, 5, 6]
unemployment = [10.0, 9.5, 8.8, 7.8, 7.2, 5.8]
deficit = [12.8, 12.2, 10.7, 9.3, 6.4, 5.8]
plt.plot(year, unemployment, color='r', marker='o', linestyle='--',
linewidth = 2.0, label='unemployment')
plt.plot(year, deficit, color='b', marker='o', linestyle='--',
linewidth = 2.0, label='deficit (%GDP)')
plt.title('sdfsdfsdf')
plt.xlabel('x one')
plt.ylabel('y one')
plt.legend(loc='upper right')
plt.grid()
plt.show()
Sample.txt的:
1 , 10.0 , 12.8
2 , 9.5 , 12.2
3 , 8.8 , 10.7
4 , 7.8 , 9.3
5 , 7.2 , 6.4
6 , 5.8 , 5.8
答案 0 :(得分:0)
试试这个,
year = list()
unemployment = list()
deficit = list()
with open('test.txt', 'r') as f:
for line in f:
strlist = line.strip().split(',')
year.append(int(strlist[0]))
unemployment.append(float(strlist[1]))
deficit.append(float(strlist[2]))
使用matplotlib代码生成,
答案 1 :(得分:0)
提供.txt
文件的格式,至少有两个选项:
csv
library。loadtxt()
功能。鉴于您已经在使用numpy
库,我建议使用后一种选项,它更清晰,更简单。
修改后的代码(假设sample.txt
是包含逗号分隔数据的文件的名称):
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import matplotlib.dates as mdates
year, unemployment, deficit = np.loadtxt("sample.txt", delimiter=",").transpose()
plt.plot(year, unemployment, color='r', marker='o', linestyle='--',
linewidth = 2.0, label='unemployment')
plt.plot(year, deficit, color='b', marker='o', linestyle='--',
linewidth = 2.0, label='deficit (%GDP)')
plt.title('sdfsdfsdf')
plt.xlabel('x one')
plt.ylabel('y one')
plt.legend(loc='upper right')
plt.grid()
plt.show()