【问题标题】:Matplotlib figure does not update in every loopMatplotlib 图不会在每个循环中更新
【发布时间】:2021-11-10 12:06:35
【问题描述】:

我想为循环中的每次迭代更新 matplotlib 的图形。它适用于大约前 30 次迭代,但随后更新停止,尽管有更多迭代。

下面你可以找到我的图代码:

import numpy as np
import matplotlib.pyplot as plt


class SimpOutput:
    fig = None
    ax_l = None
    ax_r = None

    it_container = []
    obj_container = []

    def __init__(self):
        self.fig, (self.ax_l, self.ax_r) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
        self.ax_l.set_title("Flexibility $c$")
        self.ax_l.set_ylabel("obj. value $c$")
        self.ax_l.set_xlabel("Iteration")

        self.ax_r.set_title("Shape")

        self.fig.show()

    def update(self, iteration, obj, x):

        self.it_container.append(iteration)
        self.obj_container.append(obj)

        self.ax_l.plot(self.it_container, self.obj_container, c="r")

        x = x.reshape((4, 4))
        x = x.T
        x = np.flip(x, 0)
        self.ax_r.imshow(x, cmap="binary")
        plt.pause(0.1)
        self.fig.show()
        plt.pause(0.1)

if __name__ == "__main__":
    out = SimpOutput()

    for i in range(50):

        out.update(i, 1000 * np.random.rand(), np.random.rand(16))

update 在每个循环中被调用。

使用fig.canvas.show() 和不同的暂停值不会影响更新。此外,set_array()set_data() 方法也不能解决问题。调试时,每次迭代都会更新图形。我用 PyCharm 编写代码。

有没有人有同样的问题,或者更确切地说,有没有人知道如何解决这个问题?

提前致谢!

最佳,

塞巴斯蒂安

【问题讨论】:

  • 包括一个可重现的例子
  • 哦,对不起!刚刚为 update() 添加了一个带有随机可能值的简单循环。

标签: python matplotlib


【解决方案1】:

我尝试运行以下简单代码:

for i in range(50):
    plt.clf()
    pd.DataFrame([3,4,i]).plot.line(title=f'iteration {i}')
    plt.show()

不更新任何图形,只是清除旧图形并绘制一个新图形。

它也会在 30 次迭代后停止创建新图形。和你一样的问题。

我怀疑问题出在 pycharm 中,所以我又尝试了一件事。

我将plt.show() 替换为plt.savefig(f'example_{i}.jpg')。它确实保存了文件夹中的所有 50 个数字(意味着它工作正常),此外,它还给了我一个警告:

envs\my_main_env\lib\site-packages\pandas\plotting\_matplotlib\core.py:337: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  fig = self.plt.figure(figsize=self.figsize)

表明问题在于并行打开的图形数量。你可以用谷歌搜索警告找到一些答案(例如warning about too many open figures)。

我在代码开头添加了参数:plt.rcParams.update({'figure.max_open_warning': 60})

现在,再次运行。在科学模式下的 pycharm 中,它不起作用。所以我关闭了科学模式(为每个情节打开一个新人物),现在它运行良好!所以我认为这个限制是pycharm对科学模式的限制——可以同时打开多少个图形。

通过转到设置->工具->Python Scientific->关闭绘图的科学模式->取消选中“在工具窗口中显示绘图”框。

这对我有用。我不知道如何在科学模式下更改限制(如果可能的话)。我相信它为您提供了足够的见解来解决您的问题 - 无论是通过保存数字还是在没有科学模式的情况下绘制它们。

【讨论】:

  • 感谢您快速详细的回答。我非常感谢你。在我的情况下,取消选中“在工具窗口中显示绘图”效果很好。
猜你喜欢
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多