为什么文本不以交互方式显示

why doesn't the text show up interactively

来自 Is there a way of drawing a caption box in matplotlib

from matplotlib import pyplot as plt
import numpy as np

x = np.arange(0,3,.25)
y = np.sin(x)
txt = '''
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
    culpa qui officia deserunt mollit anim id est laborum.'''

fig = plt.figure()
ax1 = fig.add_axes((.1,.4,.8,.5))
ax1.bar(x,y,.2)
fig.text(.1,.1,txt) #<-doesn't work interactively
#plt.show()

如果我 运行 将此代码用作脚本,则此代码有效。但是如果我首先 运行 一切,但不包括 fig.text 行,然后我将 fig.text 行输入控制台, txt 不会出现在图!为什么?

通读 this information on interactive mode in matplotlib. It either needs to be turned on by default in your matplotlibrc file, set via matplotlib.interactive(), or turned on in your console by running plt.ion(),这是我在这里推荐的内容。不过,从长远来看,使用自定义 matplotlibrc 文件是最好的选择。

这是一个功能,不是错误。

重新绘制图形的计算量可能非常大,因此 OO 接口不会强制重新绘制图形。通过推迟绘图的开销,您可以大大提高对 FigureAxes 方法进行多次调用的函数的性能。要让屏幕上的图形更新以反映您需要显式更新它的状态。您通过

以编程方式强制重新绘制
fig.canvas.draw()

plt.draw()

这将重绘 'current figure'。调整 window 的大小将导致 GUI 框架重新绘制它的 window,这反过来会触发 mpl 图的完全重新绘制。

当您使用 pyplot 函数(而不是 OO 接口)时,每个 绘图命令都会强制重绘。这种差异是因为 pyplot 接口与状态机(跟踪您当前的 figure/axes)相结合,并且是为交互使用而设计的,而 OO 接口(pyplot 接口是构建的)在之上)专为编程使用而设计。

开发人员意识到这是一个烦恼,near/mid 术语路线图(请参阅 https://github.com/matplotlib/matplotlib/pull/3587 和其中的链接)使这种行为更直观一些。