[英]How can I plot a growing data file in real-time with matplotlib?
我正在嘗試實時繪制一個文件 ( datos.txt
),該文件將不斷從 pH 傳感器獲取新數據。
如圖所示這里,我能夠繪制數據文件,但我仍然無法做到這一點的實時性。 我正在使用以下代碼:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np
# Converter function
datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%d-%m-%Y %H:%M:%S'))
# Read data from 'file.dat'
dates, levels = np.genfromtxt('/home/ramiro/Programas/pythonProgs/datos.txt', # Data to be read
delimiter=19, # First column is 19 characters wide
converters={0: datefunc}, # Formatting of column 0
dtype=float, # All values are floats
unpack=True) # Unpack to several variables
fig = plt.figure()
ax = fig.add_subplot(111)
# Configure x-ticks
ax.set_xticks(dates) # Tickmark + label at every plotted point
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax.locator_params(axis='x',nbins=10)
ax.plot_date(dates, levels, ls='-', marker='o')
ax.set_title('Hora')
ax.set_ylabel('pH')
ax.grid(True)
# Format the x-axis for dates (label formatting, rotation)
fig.autofmt_xdate(rotation=45)
fig.tight_layout()
plt.show()
我看過一些實時繪圖的例子,但我不知道如何讓我的工作
你可以將你的情節包裝成一個animate
函數,如下所示:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.animation as animation
from datetime import datetime
import numpy as np
def animate(i, fig, ax):
# Converter function
datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%d-%m-%Y %H:%M:%S'))
# Read data from 'file.dat'
dates, levels = np.genfromtxt('/home/ramiro/Programas/pythonProgs/datos.txt', # Data to be read
delimiter=19, # First column is 19 characters wide
converters={0: datefunc}, # Formatting of column 0
dtype=float, # All values are floats
unpack=True) # Unpack to several variables
# Configure x-ticks
ax.set_xticks(dates) # Tickmark + label at every plotted point
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax.locator_params(axis='x',nbins=10)
ax.plot_date(dates, levels, 'k', ls='-', marker='o')
ax.set_title('Hora')
ax.set_ylabel('pH')
ax.grid(True)
# Format the x-axis for dates (label formatting, rotation)
fig.autofmt_xdate(rotation=45)
fig.tight_layout()
fig = plt.figure()
ax = fig.add_subplot(111)
ani = animation.FuncAnimation(fig, animate, fargs=(fig, ax), interval=1000)
plt.show()
這將每秒重新讀取並顯示您的情節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.