【问题标题】:Continue in parent for loop在父 for 循环中继续
【发布时间】:2014-06-23 09:42:40
【问题描述】:

我有一个 for 循环,我在其中创建并显示一个 matplotlib 图。我还有一个嵌套函数 (def onClick),它处理当我单击图时发生的事情。

例如

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 循环的一部分..

任何帮助将不胜感激。

【问题讨论】:

  • 您希望在循环体中的哪一点跳转到循环的下一次迭代?
  • 问题是不能调用 plt.show() 两次。

标签: python matplotlib


【解决方案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()

【讨论】:

  • 谢谢。如果我不止一次调用 show() 真的那么糟糕吗?该部分目前工作正常,我只需要在单击六次后继续 for 循环。
  • Praxeolitoc,当我手动关闭窗口跳到下一个循环时它会起作用,我猜你的意思是如果我自动执行它就不会起作用?
  • 其实这让我很吃惊。对我来说,一旦我调用 plt.show() 并关闭后续调用将被忽略。如果这对您有用并且方便,那么您不妨使用它,只要您知道它在某些机器上可能不起作用。
猜你喜欢
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 2015-05-27
  • 1970-01-01
相关资源
最近更新 更多