是否可以更新 Python (Spyder) 中的内联图?

Is it possible to update inline plots in Python (Spyder)?

设置:Anaconda 3 (Win10 64)、Spyder 4 和 Python 3.7。 IPython 图形设置是默认设置(内联)。我还是 Python 的新手,但我环顾四周,到目前为止还没有找到解决我问题的答案。提前谢谢大家。

因此,在此设置中,每当我使用 matplotlib 创建绘图时,它都会出现在 Spyder 的绘图窗格中。例如

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')

创建箱线图。现在,如果我想为情节添加标题,代码将是

bp.set_title("This Title")

这是我遇到的一些问题。如果我 运行 整个块在一起

df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')
bp.set_title("This Title")

然后我得到一个以 "This Title" 为标题的箱形图,显示在绘图窗格中, which is what I want.

但是,如果我 运行 在 IPython 控制台中逐行执行上述代码,第二行将按预期生成箱线图,但第三行不会对绘图窗格中的图像,因此 the image in the plot pane still do not have a title

现在,如果我转到工具 > 首选项 >IPython 控制台 > 图形并将图形后端设置为自动而不是默认的内联,那么当我 运行 控制台行中的代码时按行,我得到一个在另一个 window 中弹出的图像,并且它 确实 update/refreshes 基于输入到控制台的新行。我知道内联图应该是静态的,但我想我看到另一个 post 有人说 可以 更新内联图?所以现在我的问题是:

  1. 如果图形后端不是像内联那样静态,则在IPython控制台中仅按行代码绘制update/refresh?
  2. 为什么当我 运行 代码块与逐行代码时得到不同的结果?
  3. 如果可以更新内联图(最好是在 Spyder 的绘图窗格中),您是怎么做到的?我已经尝试了各种方法来重新绘制地块,例如
plt.show()
plt.draw()
bp.get_figure().canvas.draw()

但其中 none 会更新绘图窗格中的图像。我想即使我不能更新图像,我至少应该能够重绘它(即第二张图像出现在具有更新特征的绘图窗格)。但到目前为止,我尝试过的任何事情都没有奏效。请多多指教,再次感谢。

(这里是 Spyder 维护者) 关于你的问题:

Do plots only update/refresh by line codes in the IPython console if the Graphics Backend is not static like inline?

正确。

Why do I get different result when I run code blocks vs line by line?

因为当您 运行 代码单元格(我认为您的意思是 "code blocks")时,您的绘图显示在该代码的末尾,因此它需要您所做的所有修改在中间行中。

If it is possible to update the inline plots (preferably in the plot pane of Spyder), how do you do it?

不,这不可能。正如您在上面正确提到的,内联图是静态图像,因此无法修改。