如何使用matplotlib实时绘制不断增长的数据文件?

时间:2017-01-13 06:19:59

标签: python matplotlib plot

我试图实时绘制一个文件(datos.txt),该文件将不断从pH传感器获取新数据。

如图here所示,我能够绘制数据文件,但我仍然无法实时完成。我使用以下代码:

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()

我已经看过一些实时绘图的例子,但我无法弄清楚如何让我的工作

1 个答案:

答案 0 :(得分:1)

您可以将您的情节包装成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() 

这会每秒重读并显示你的情节。