我想用matplotlib更新一个线图,并且想知道,如果对代码进行了很好的修改,那么绘制的线只会更新而不是每次重绘。以下是示例代码:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
matplotlib.style.use('ggplot')
plt.ion()
fig=plt.figure()
i=0
df = pd.DataFrame({"time": [pd.datetime.now()], "value": 0}).set_index("time")
plt.plot(df);
while True:
temp_y=np.random.random();
df2 = pd.DataFrame({"time": [pd.datetime.now()], "value": temp_y}).set_index("time")
df = df.append(df2)
plt.plot(df)
i+=1
plt.show()
plt.pause(0.000001)
如您所见,一段时间后绘图变得越来越慢,我认为每次迭代都会重新绘制折线图,因为它会改变颜色。
答案 0 :(得分:2)
是
x = np.arange(10)
y = np.random.rand(10)
line, = plt.plot(x,y)
line.set_data(x,np.random.rand(10))
plt.draw()
但是,您的绘图变慢了,因为您正在扩展数据框,并且每个追加操作可能会将内存中的帧复制到新位置。随着数据框大小的增加,复制操作需要更长时间。我会循环索引并绘制(for ii in range(len(data)): line.set_data(x[:ii], y[:ii])
)
编辑:
import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd
n = 100
x = np.arange(n)
y = np.random.rand(n)
# I don't get the obsession with pandas...
df = pd.DataFrame(dict(time=x, value=y))
# initialise plot and line
line, = plt.plot(df['time'], df['value'])
# simulate line drawing
for ii in range(len(df)):
line.set_data(df['time'][:ii], df['value'][:ii]) # couldn't be bothered to look up the proper way to index in pd
plt.draw()
plt.pause(0.001)
答案 1 :(得分:0)
您可以将以下代码用于matplotlib中的实时绘图
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
x_vals = []
y_vals = []
index = count()
def analyse(i):
data = pd.read_csv(<your file which is updated or live data>)#u can use the pandas or any other data frame work
x = data['index']
y1 = data['readings']
plt.cla()
plt.plot(x, y1, label='Temperature') #in my case data is temperature
plt.legend(loc='upper left')
plt.tight_layout()
ani = FuncAnimation(plt.gcf(), analyse, interval=1000) #adjust intervals for call
plt.tight_layout()
plt.show()