我认为你的代码的问题是你调用fig, ax = plt.subplots()
每次刷新数据时。这创建了一个新的Figure https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure每次,您都会看到新的框架弹出。
相反,您想要创建Figure https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure在你之外的while
循环,并且只刷新Axes https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes一旦你加载了新数据。
我使用了您提供的基本示例来创建一个自动更新Figure https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
data = [
{'timestamp': '2017-05-11 16:21:55', 'A': 0.724931, 'B': 0.361333, 'C': 0.517720},
{'timestamp': '2017-05-11 16:22:25', 'A': 0.725386, 'B': 0.360833, 'C': 0.518632},
{'timestamp': '2017-05-11 16:22:55', 'A': 0.725057, 'B': 0.361333, 'C': 0.521157},
{'timestamp': '2017-05-11 16:23:25', 'A': 0.724402, 'B': 0.362133, 'C': 0.520002},
]
df = pd.DataFrame(data)
df.set_index("timestamp")
plt.ion()
fig, ax = plt.subplots()
while True:
dframe = df.copy()
dframe['timestamp'] = pd.to_datetime(dframe['timestamp']) + pd.DateOffset(hours=2)
dframe = dframe.set_index('timestamp')
end = dframe.index.max()
start= end.to_datetime() - dt.timedelta(hours=1)
dframe = dframe.loc[start:end]
plt.pause(0.0001)
ax.plot_date(dframe.index.to_pydatetime(), dframe, marker='', linestyle='solid')
Edit 1
我无法重现所提出的Warning https://docs.python.org/2/library/exceptions.html#exceptions.Warning,但我的猜测是它与pause https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.pause.html#matplotlib.pyplot.pause称呼。也许尝试交换以下内容并编辑暂停时间。
ax.plot_date(dframe.index.to_pydatetime(), dframe, marker='', linestyle='solid')
plt.pause(0.01)
Edit 2
修复颜色非常简单。定义您的调色板,然后从中进行选择。
colors = ['r', 'g', 'b']
plt.ion()
fig, ax = plt.subplots()
while True:
dframe = df.copy()
# Your data manipulation
# ...
dframe = dframe.loc[start:end]
for i, column in enumerate(dframe.columns):
ax.plot(dframe.index.to_pydatetime(), dframe[column], color=colors[i], marker=None, linestyle='solid')
plt.pause(0.1)
如果您有更多列,请向其中添加更多颜色colors
大批。或者,根据中的列数动态生成它dframe
.