【问题标题】:multiple figures generated by python loop but drawn only after loop endspython循环生成的多个图形,但仅在循环结束后绘制
【发布时间】:2016-10-05 03:19:43
【问题描述】:

我有以下代码,它采用对象列表,并为每个对象从对象中存储的数据中绘制一个图形:

def Plot(self, *figures , wait = True):


    def plot(fig,n):
        fig.fig = plt.figure(n)
        print("Ploting figure {} for file {}\n".format(n,fig.name))
        fig.Plot()
        plt.show()
        if wait:
            input("Press Enter to continue to next figure")

    if not figures:
        figures = self.figures            
        for n,fig in figures.items():
            plot(fig,n)
    else:
        for n,fig in enumerate(figures):
            plot(fig,n)

fig.Plot() 是处理绘图的函数。运行“绘图”时,循环的每次迭代都会生成一个图形,但实际绘制仅在循环完成后发生。

我想要实现的是,在每次迭代中都会生成图形并在继续下一次迭代之前绘制绘图。

【问题讨论】:

  • 经过一番谷歌搜索后,我在physicalmodelingwithpython.blogspot.co.il/2015/07/… 找到了一个解决方案,其中行:“if wait: input("Press Enter to continue to next figure")”应替换为:“while True : if plt.waitforbuttonpress(): break"
  • 请发表您的评论作为答案。

标签: python loops matplotlib plot iteration


【解决方案1】:

经过一番谷歌搜索后,我在以下位置找到了一个解决方案:physicalmodelingwithpython.blogspot.co.il/2015/07/... 应替换以下行:“if wait: input("Press Enter to continue to next figure")” with: "while True: if plt.waitforbuttonpress(): break"

plt.waitforbuttonpress() 返回 True 是一个键被按下,如果鼠标按钮被按下则返回 False 允许停止函数中的循环并返回到控制台。

我添加了关键字“Startat”,以便以后能够从列表中的下一个图恢复(这也可以通过合适的装饰器来完成)。

一个更优雅的解决方案可能可以使用 python 事件处理例程来实现,我和 John Snow 一样了解。

完整的Function(部分关键词与原题无关):

def Plot(self, figures=None, wait=True, Save=False, Legendtitle=False, Startat=0):

    def plot(fig, n):

        print("Ploting figure {} for file {}\n".format(n, fig.name))
        fig.Plot(Legendtitle)
        if Save:
            fig.SavePlot()   
        if wait:    
            while True:
                if plt.waitforbuttonpress():
                    break
                else:
                    return True


    if not figures:
        figures = self.figures
        for n, fig in figures.items(): 
            if n>= Startat:                   
                if plot(fig, n):
                    break


    else:
        for n, fig in enumerate(figures):
            if n>= Startat:
                if plot(fig, n):
                    break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多