【发布时间】:2016-10-10 09:55:20
【问题描述】:
这可能很明显,所以提前对这个小问题表示抱歉。我想用 matplotlib.pyplot 动态更新时间序列。更准确地说,我想在 while 循环中绘制新生成的数据。
这是我目前的尝试:
import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd
import time
n = 100
x = np.NaN
y = np.NaN
df = pd.DataFrame(dict(time=x, value=y), index=np.arange(n)) # not neccessarily needed to have a pandas df here, but I like working with it.
# initialise plot and line
line, = plt.plot(df['time'], df['value'])
i=0
# simulate line drawing
while i <= len(df):
#generate random data point
newData = np.random.rand()
# extend the data frame by this data point and attach the current time as index
df.loc[i, "value"] = newData
df.loc[i, "time"] = pd.datetime.now()
# plot values against indices
line.set_data(df['time'][:i], df['value'][:i])
plt.draw()
plt.pause(0.001)
# add to iteration counter
i += 1
print(i)
这将返回 TypeError: float() argument must be a string or a number, not 'datetime.datetime'。但据我所知,matplotlib 在 x 轴 (?) 上绘制日期没有任何问题。
非常感谢。
【问题讨论】:
-
pandas.plot不是无缝绘制日期的吗?无论如何,there's a chapter in the matplotlib docs 用于与日期相关的绘图。 This example 使用ax.plot_date。
标签: python matplotlib plot while-loop