【发布时间】:2018-04-04 18:19:01
【问题描述】:
我有一些 csv 文件,其中包含我想要绘制的数据。我想使用键盘上的箭头键覆盖绘图。
我的代码:
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])
我的问题是:当我按下按钮时,会打开一个新窗口,而不是覆盖绘图。
有什么建议吗?
[编辑](我想保留以前的代码,因为这种方法的错误是不同的)我在 DavidG 的评论之后的代码看起来像:
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])
当我按下或按下时,这里没有任何反应。
【问题讨论】:
-
在每次调用
plotter时,您都会使用fig = plt.figure()创建一个新图形。您可能想创建一个带有子图的图形,然后不断更新该图形 -
我添加了另一种方法,我只创建了一次新图形。这一次,当我按下一个按钮时,什么也没有发生。
-
使用
plt.savefig('single_image.png')?
标签: python python-3.x matplotlib