Reputation: 10398
I am trying to plot online data coming from two different sources in this way:
In each iteration:
1] first source: add incoming data to the graph.
2] second source: delete previous data and keep only the incoming ones in the graph.
I gave a try to plotly but the problem is that you can't delete data once it have been plotted (I need this for the incoming data from the second source).
Inspired from @WakkaDojo answer here is the final code where I used malplotlib.animation:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import matplotlib.animation as animation
import random
from sklearn.datasets.samples_generator import make_blobs
fig = plt.figure()#figsize=(7,4), dpi=100
ylim(0,20)
xlim(0,20)
def data_gen():
centers = [[15, 15],[5, 5]]
for i in range(1000):
X, _ = make_blobs(n_samples=2, centers=centers, cluster_std=1.0,center_box=(-1, 1))
print i
yield float(X[0][0]), float(X[0][1]), float(X[1][0]), float(X[1][1])
updated_source_1, = plot([], [], linestyle='none', marker='o', color='g')
updated_source_2, = plot([], [], linestyle='none', marker='o', color='r')
ax = gca()
source_1_xdata, source_1_ydata = [], []
source_2_xdata, source_2_ydata = [0], [0]
def run(data):
x0,y0,x1,y1 = data
# remove previous plotted data
source_2_xdata.remove(xdata1[len(xdata1)-1])
source_2_ydata.remove(ydata1[len(ydata1)-1])
# append new data
source_1_xdata.append(x0)
source_1_ydata.append(y0)
source_2_xdata.append(x1)
source_2_ydata.append(y1)
updated_source_1.set_data(source_1_ydata, source_1_xdata)
updated_source_2.set_data(source_2_ydata, source_2_xdata)
return updated_source_1, updated_source_2,
ani = animation.FuncAnimation(fig, run, data_gen, interval=100)
plt.show()
Upvotes: 0
Views: 595
Reputation: 431
A simpler way to "delete" data already plotted would be to just replot the data. Think of storing your data in lists, where you can easily add or remove data, and then just replot as updates come in.
A simple way to keep the latest N points in a list is
def add_data (new_data, old_data, n): # keep n points
return (old_data + new_data)[-n:]
Upvotes: 1