【问题标题】:matplotlib update plot in while-loop with dates as x-axismatplotlib在while循环中更新绘图,日期为x轴
【发布时间】: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 轴 (?) 上绘制日期没有任何问题。

非常感谢。

【问题讨论】:

标签: python matplotlib plot while-loop


【解决方案1】:

正如 Andras Deak 指出的那样,您应该明确告诉 pandas 您的 time 列是日期时间。当您在代码末尾执行df.info() 时,您会看到它采用df['time'] 作为float64。您可以通过df['time'] = pd.to_datetime(df['time']) 实现此目的。

我能够让您的代码运行,但我必须添加几行代码。我在 iPython (Jupyter) 控制台中运行它,并且没有 autoscale_viewrelim 这两行,它没有正确更新绘图。剩下要做的是很好地格式化 x 轴标签。

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.
df['time'] = pd.to_datetime(df['time']) #format 'time' as datetime object

# initialise plot and line
fig = plt.figure()
axes = fig.add_subplot(111)
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, use autoscale_view and relim to readjust the axes
    line.set_data(df['time'][:i], df['value'][:i])
    axes.autoscale_view(True,True,True)
    axes.relim()
    plt.draw()

    plt.pause(0.01)

    # add to iteration counter
    i += 1

    print(i)

【讨论】:

  • 美丽。谢谢!
  • 能否请您编辑您的示例,使 x 轴正确显示日期时间?
  • 我试过了,但我很挣扎。不知何故,set_major_formatter 使用 matplotlib.dates 的常用方法不适用于 pandas 数据帧的时间格式,当我使用浮点数据帧时,它会再次导致你的浮点错误。我明天也许可以再试一次,但如果你自己想不通,最好创建一个新问题,因为这个问题已经被接受(尽管人们可能只是将你称为“matplotlib 动画”)。
猜你喜欢
  • 2020-06-09
  • 2018-08-31
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多