runnerpaul
runnerpaul

Reputation: 7196

Prevent lines joining back to start with Matplotlib

How do I prevent my plot lines from joining back to the start when I run my Python program?

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')

data = pd.read_csv('csv_data.csv')
x_vals = []
y_vals1 = []
y_vals2 = []

index = count()


def animate(i):
    x = data['x_value']
    y1 = data['total_1']
    y2 = data['total_2']
    x_vals.append(x[i])
    y_vals1.append(y1[i])
    y_vals2.append(y2[i])

    plt.cla()
    plt.plot(x_vals, y_vals1, label='Channel 1')
    plt.plot(x_vals, y_vals2, label='Channel 2')

    plt.legend(loc='upper left')

    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, frames=len(data.index), interval=100)

plt.show()

enter image description here

Upvotes: 1

Views: 188

Answers (1)

david
david

Reputation: 1501

The animation function loops using infinitely frame value from 0 to len(data.index)-1. In the animate function, you keep on adding values to three lists: they become larger and larger...

You can reinitialize each list x_vals, y_vals1 and y_vals_2 when i==0 wiith these kind of definitions:

x_vals = x[0:i]
y_vals1 = y1[0:i]
y_vals2 = y2[0:i]

or You can use repeat=False option of FuncAnimation

Upvotes: 2

Related Questions