Sunday, 22 December 2019

matplotlib live plot, save plot as gif, data in csv


#data_gen
#generate 3 columns of live data, 10 rows/sec , save in csv file

import csv
import random
import time

x_value = 0
total_1 = 1000
total_2 = 1000

fieldnames = ['x_value', 'total_1', 'total_2']

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

while True:
    #append a row of data to file every 100ms
    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        info = {
            'x_value': x_value,
            'total_1': total_1,
            'total_2': total_2
        }

        csv_writer.writerow(info)
        print(x_value, total_1, total_2)

        x_value += 1
        total_1 += random.randint(-10, 10)
        total_2 += random.randint(-10, 10)

    time.sleep(0.1)

----------------------------------
#data_plot
#load live data from csv every second, plot and save 

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

def animate(i):
    data = pd.read_csv('data.csv')
    x = data['x_value']
    y1 = data['total_1']
    y2 = data['total_2']

    plt.cla()
    plt.plot(x, y1, label='Channel 1')
    plt.plot(x, y2, label='Channel 2')

    plt.legend(loc='upper left')

#every second update graph, save 50 frames
ani = FuncAnimation(plt.gcf(), animate, frame=50, interval=1000)

#save plot as gif, 10 frame/second
ani.save('./animation.gif', fps=10)

plt.tight_layout()
plt.show()

------------------------
#data.csv

x_value,total_1,total_2
0,1000,1000
1,1008,1010
2,1004,1007
3,997,998
4,993,1006
5,985,1010
6,980,1015
7,972,1024
8,980,1030
9,984,1027
10,986,1020
11,987,1014
12,977,1016
13,976,1012
14,984,1002
15,976,993
16,985,983
17,986,988
18,986,997
...

reference:
https://www.youtube.com/watch?v=Ercd-Ip5PfQ&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB_&index=9
http://louistiao.me/posts/notebooks/save-matplotlib-animations-as-gifs/

No comments:

Post a Comment