How do I dynamically draw existing points from a data set in a Python program

Viewed 220

I've this Python script to dynamically update a chart as values are added to a csv file:


import numpy as np
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 animate(i):
    data = pd.read_csv('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')

    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, frames=np.arange(0, 11, 0.1), interval=1000)

plt.show()

This is what my csv data initially looks like:

x_value,total_1,total_2
0,1000,1000
1,1002,1001
2,1004,999
3,1006,1004
4,1002,1003
5,999,1003
6,1003,1001
7,1011,1004
8,1008,1000
9,1010,1000
10,1012,999

If I run my program the chart appears with all 11 points for each line and dynamically adds each new one after that. Is it possible to edit this code so that the initial 11 points get drawn dynamically when the program is run and if so how do I do that? I wish for each point to be drawn every second.

1 Answers

This is one way you could get the 11 points to get drawn dynamically at every 1 second interval

import numpy as np
from itertools import count
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

plt.figure()

data = pd.read_csv('csv_data.csv')
x = data['x_value']
y1 = data['total_1']
y2 = data['total_2']

line1 = plt.plot(x[0], y1[0], 'ok', lw=1.5, label='Channel 1',color='black')
line2 = plt.plot(x[0], y2[0], '+', lw=1.5, label='Channel 2',color='red')
plt.title('Channels', fontsize=16)
plt.ylabel('Channel', fontsize=12)
plt.xlabel('x_value', fontsize=12)

plt.ion()   # set interactive mode
plt.show()
for i, item in data.iterrows():

    line1 = plt.plot(x[i], y1[i], 'ok', lw=1.5,color='black')
    line2 = plt.plot(x[i], y2[i], '+', lw=1.5,color='red')
    plt.legend()
    plt.gcf().canvas.draw()
    plt.pause(1)
Related