继续在父级循环

时间:2014-06-23 00:40:38

标签: python matplotlib

我有一个for循环,我在其中创建并显示一个matplotlib图。我还有一个嵌套函数(def onClick),它可以处理当我点击图形时会发生什么。

E.g。

for i in list:
    fig, ax = plt.subplots(1)
    plt.plot(data)

    def onClick(event):
        #doSomething = True

    cid = fig.canvas.mpl_connect('button_press_event', onclick)

    plt.show()

我希望能够在6次点击后继续for循环到下一次迭代。我不能将continue语句放在onClick函数中,因为它不是for循环的一部分。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

首先,plt.show()被调用一次(参见here on Stackoverflowhere on the Matplotlib mailing list)。这简直就是如何使用Matplotlib。你准备你的情节,然后plt.show()是脚本中的最后一行。

但是,如果我们想展示并与多个情节互动怎么办?诀窍是提前准备图表,并在结束时仍然调用plt.show()一次。以下是使用代码中的onclick事件的示例。它循环几个图,然后在结束时停止。您必须稍微重新排列代码以保存for循环中发生的任何结果。

import numpy as np
import matplotlib.pyplot as plt

# prepare some pretty plots
stuff_to_plot = []
for i in range(10):
    stuff_to_plot.append(np.random.rand(10))

fig = plt.figure()
ax = fig.add_subplot(111)

coord_index = 0
plot_index = 0
def onclick(event):
    # get the index variables at global scope
    global coord_index
    if coord_index != 6:
        print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
            event.button, event.x, event.y, event.xdata, event.ydata)
        coord_index += 1
    else:
        coord_index = 0
        global plot_index
        # if we have more to plot, clear the plot and plot something new
        if plot_index < len(stuff_to_plot):
            plt.cla()
            ax.plot(stuff_to_plot[plot_index])
            plt.draw()
            plot_index += 1

cid = fig.canvas.mpl_connect('button_press_event', onclick)

# plot something before fist click
ax.plot(stuff_to_plot[plot_index])
plot_index += 1
plt.show()
相关问题