[英]How to read data from local txt file in python live plot
在這段代碼中,我不想在代碼端寫數據。 我如何從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
嘗試這個,
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代碼,它會產生,
提供.txt
文件的格式,至少有兩個選項:
鑒於您已經在使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.