在函数中使用Matplotlib Plot和小部件并返回用户输入

时间:2018-07-27 09:38:29

标签: python matplotlib matplotlib-widget

我的问题如下:

我创建了一个Matplotlib图形,其中包括一些小部件滑块和一个用于关闭图形的按钮。这可行。我该怎么做才能在返回例如单击“关闭图形”按钮后幻灯片的值是什么?

这是代码(im3d是3d图像numpy数组):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

class IndexTracker(object):
    def __init__(self, ax, data3d, title):
        self.ax = ax
        ax.set_title(title)

        self.data3d = data3d
        rows, cols, self.slices = data3d.shape
        self.ind = self.slices//2

        self.im = ax.imshow(self.data3d[:, :, self.ind])
        self.update()

    def update(self):
        self.im.set_data(self.data3d[:, :, self.ind])
        ax.set_ylabel('slice %s' % self.ind)
        self.im.axes.figure.canvas.draw()
#
fig = plt.figure(figsize=(18, 8), dpi=80, facecolor='w', edgecolor='b')
ax  = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

tracker1 = IndexTracker(ax, im3d, 'Select First Image')
tracker2 = IndexTracker(ax2, im3d, 'Select Last Image')

def slider_changed(value, tracker):
    numb = int(round(value))    
    tracker.ind = numb    
    tracker.update()

max0 = im3d.shape[2] -1

ax_start  = fig.add_axes([0.1, 0.85, 0.35, 0.03])
sl_start = Slider(ax_start, 'START', 0, max0, valinit=0, valfmt="%i")

ax_end  = fig.add_axes([0.6, 0.85, 0.35, 0.03])
sl_end = Slider(ax_end, 'END', 0, max0, valinit=0, valfmt="%i")

def sl_start_changed(val):
    slider_changed(sl_start.val,tracker1)

def sl_end_changed(val):
    slider_changed(sl_end.val,tracker2)

sl_start.on_changed(sl_start_changed)
sl_end.on_changed(sl_end_changed)

class Index(object):

    def close_figure(self, event):
        plt.close(fig)    

callback = Index()
ax_button = fig.add_axes([0.7, 0.06, 0.15, 0.075])
button = Button(ax_button, 'DONE')
button.on_clicked(callback.close_figure)
fig.canvas.manager.window.raise_()

plt.plot()

我的第一个想法是在plt.plot()之后运行while循环,如下所示:

while not_done:
   time.sleep(0.5)

,然后在函数close_figure中将not_done更改为False。但是在这种情况下,该图不显示。

1 个答案:

答案 0 :(得分:1)

关闭图形后,滑块仍然可用。因此,您只需在关闭图形后即可访问其val属性

fig, ax = plt.subplots()

slider = Slider(...)

# .. callbacks

plt.show() # you may use plt.show(block=True) when this is run in interactive mode

print(slider.val)

澄清后进行编辑:

您正在运行spyder,并在其中使用IPython控制台。这有几个含义。

  • 您需要关闭互动模式plt.ioff()
  • 您需要停用matplotlib的“支持”

enter image description here

然后下面的代码运行正常,并且仅在关闭图形后才打印值。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

plt.ioff()

im3d = np.random.rand(20,20,10)


class IndexTracker(object):
    def __init__(self, ax, data3d, title):
        self.ax = ax
        ax.set_title(title)

        self.data3d = data3d
        rows, cols, self.slices = data3d.shape
        self.ind = self.slices//2

        self.im = ax.imshow(self.data3d[:, :, self.ind])
        self.update()

    def update(self):
        self.im.set_data(self.data3d[:, :, self.ind])
        ax.set_ylabel('slice %s' % self.ind)
        self.im.axes.figure.canvas.draw()
#
fig = plt.figure(figsize=(18, 8), dpi=80, facecolor='w', edgecolor='b')
ax  = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

tracker1 = IndexTracker(ax, im3d, 'Select First Image')
tracker2 = IndexTracker(ax2, im3d, 'Select Last Image')

def slider_changed(value, tracker):
    numb = int(round(value))    
    tracker.ind = numb    
    tracker.update()

max0 = im3d.shape[2] -1

ax_start  = fig.add_axes([0.1, 0.85, 0.35, 0.03])
sl_start = Slider(ax_start, 'START', 0, max0, valinit=0, valfmt="%i")

ax_end  = fig.add_axes([0.6, 0.85, 0.35, 0.03])
sl_end = Slider(ax_end, 'END', 0, max0, valinit=0, valfmt="%i")

def sl_start_changed(val):
    slider_changed(sl_start.val,tracker1)

def sl_end_changed(val):
    slider_changed(sl_end.val,tracker2)

sl_start.on_changed(sl_start_changed)
sl_end.on_changed(sl_end_changed)

class Index(object):

    def close_figure(self, event):
        plt.close(fig)    

callback = Index()
ax_button = fig.add_axes([0.7, 0.06, 0.15, 0.075])
button = Button(ax_button, 'DONE')
button.on_clicked(callback.close_figure)
fig.canvas.manager.window.raise_()

plt.show()

print(sl_start.val, sl_end.val)

或者,您可以只在外部命令行中运行完整的代码,而不需要plt.ioff()

enter image description here