I have some csv files with data I want to plot. I want to use my arrow keys on my keyboard to overwrite the plot.
My Code:
import os, pandas, glob
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog
counter = 0
class Plotter:
def __init__(self, filepath):
self.plotter(filepath)
def press(self, event):
print('press', event.key)
global counter
if event.key == 'down':
if (counter + 1) < len(files):
counter = counter + 1
self.plotter(files[counter])
if event.key == 'up':
if not (counter - 1) < 0:
counter = counter - 1
self.plotter(files[counter])
def plotter(self, filepath):
data = pandas.read_csv(filepath)
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', self.press)
ax = fig.add_subplot(111)
ax.plot(data.x, data.y1, 'r-')
ax2 = ax.twinx()
ax2.plot(data.x, data.y2, '--')
plt.show()
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
dir_path = filedialog.askdirectory()
files = list(glob.glob(os.path.join(dir_path, 'test*.csv')))
print(files[counter])
Plot = Plotter(files[counter])
My issue is: When I press the button a new window opens instead of overwriting the plot.
Any suggestions?
[EDIT](I want to keep the previous code, as the error is different with this approach) My Code after the comment from DavidG looks like:
import os, pandas, glob
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog
counter = 0
class Plotter:
def __init__(self, filepath):
self.fig = plt.figure()
self.fig.canvas.mpl_connect('key_press_event', self.press)
self.plotter(filepath)
def press(self, event):
print('press', event.key)
global counter
if event.key == 'down':
if (counter + 1) < len(files):
counter = counter + 1
self.plotter(files[counter])
if event.key == 'up':
if not (counter - 1) < 0:
counter = counter - 1
self.plotter(files[counter])
def plotter(self, filepath):
data = pandas.read_csv(filepath)
ax = self.fig.add_subplot(111)
ax.plot(data.x, data.y1, 'r-')
ax2 = ax.twinx()
ax2.plot(data.x, data.y2, '--')
plt.show()
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
dir_path = filedialog.askdirectory()
files = list(glob.glob(os.path.join(dir_path, 'test*.csv')))
print(files[counter])
Plot = Plotter(files[counter])
Here nothing happens when I press down or up.