messymon
messymon

Reputation: 33

Python: how to display dynamically changing graph matplotlib

I want to plot line graph row my row & I want the previous line to be updated by the next line (on the same frame). Here's the example of the input:

enter image description here

Here's the code that I have:

def openB():
bmFile = filedialog.askopenfile(mode='r',
                                    filetypes=(("CSV file", "*.csv"), ("All files", "*.*")),
                                    title="Select a CSV file")

bmFile2 = pd.read_csv(bmFile, header=[2])

selectCol = bmFile2.iloc[0:,3:]

selectCol.T.plot()
plt.show()

I want to plot each row, that's why I am using Transpose method on selectCol.

In order to plot row by row (dynamically changing), what function should I do? FuncAnimation or for loop (range)? and How?

Thank you. Greatly appreciated :)

Upvotes: 0

Views: 1366

Answers (2)

Red
Red

Reputation: 27557

This shows how to dynamically plot each row:

with open('file.csv','r') as f:
    lines = f.read().splitlines()

for line in lines:
    y = line.split(',')[2:]
    x = np.linspace(0,1,num=len(y))
    plt.plot(x,y)

I know this doesn't animate, but I it helps the dynamic issue.

Upvotes: 1

JakobVinkas
JakobVinkas

Reputation: 1063

You can use the plt.clf and plt.draw to plot it dynamically.

As follows for example:

import matplotlib.pyplot as plt
import numpy as np

file = np.random.normal(5,5,(1000,100))

for row in file:
    plt.clf() # Clear the current figure
    
    plt.plot(row) # Calculate and plot all you want

    plt.draw()
    plt.pause(0.1) # Has to pause for a non zero time

plt.show() # When all is done

PS: ax.clear() will clear the axis while plt.clf() will clear the entire figure.

Upvotes: 1

Related Questions