[英]How can I plot a growing data file in real-time with matplotlib?
I'm trying to plot, in real-time, a file ( datos.txt
) that will continuously get new data from a pH sensor.我正在尝试实时绘制一个文件 ( datos.txt
),该文件将不断从 pH 传感器获取新数据。
As shown here , I was able to plot a data file, but I'm still unable to do it in real time.如图所示这里,我能够绘制数据文件,但我仍然无法做到这一点的实时性。 I'm using the following code:我正在使用以下代码:
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()
I have seen some examples of real-time plotting, but I can't figure out how to make mine work我看过一些实时绘图的例子,但我不知道如何让我的工作
You could wrap your plot into an animate
function as follows:你可以将你的情节包装成一个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()
This would reread and display your plot every second.这将每秒重新读取并显示您的情节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.