matplotlib Figure.show 仅适用于pyplot管理的地物

mspsb9vt  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(187)

bounty将在7天后过期。回答此问题可获得+50声望奖励。O.Laprevote希望引起更多人关注此问题。

有关于使用matplotlib.pyplot为matplotlib 3.5.1的bug报告,所以我尝试使用matplotlib.figure.Figure来绘制图形,它工作正常。
当我无法调用plt.show时,如何在matplotlib中查看Figure的图形?调用fig.show将给予以下异常:

Traceback (most recent call last):
  File "<module1>", line 23, in <module>
  File "C:\Software\Python\lib\site-packages\matplotlib\figure.py", line 2414, in show
    raise AttributeError(
AttributeError: Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()

显示此问题的演示代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

x = np.linspace(0, 10, 500)
y = np.sin(x**2)+np.cos(x)

# ------------------------------------------------------------------------------------

fig, ax = plt.subplots()
ax.plot(x, y, label ='Line 1')
ax.plot(x, y - 0.6, label ='Line 2')
plt.show()      # It work, but I cannot use it for the scaling bug in matplotlib 3.5.1

# ------------------------------------------------------------------------------------

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot()
ax.plot(x, y, label ='Line 1')
ax.plot(x, y - 0.6, label ='Line 2')
fig.show()      # Get exception here
jv4diomz

jv4diomz1#

目前尚不清楚您的最终目标是否是:
1.只需使用fig.show()
1.或者将fig.show()专门用于原始Figure()对象

1.如果只想使用fig.show()

然后,通过将plt.show()替换为fig.show()plt.subplots()的第一个代码块将正常工作:

fig, ax = plt.subplots(figsize=(5, 4))  # if you use plt.subplots()
ax.plot(x, y, label ='Line 1')
ax.plot(x, y - 0.6, label ='Line 2')
# plt.show()
fig.show()                              # fig.show() will work just fine

2.如果您特别希望使用原始Figure()对象

那么问题就在于它缺少一个形象管理者:
如果图形不是使用pyplot.figure创建的,则它将缺少FigureManagerBase,并且此方法将引发AttributeError
这意味着您需要手动创建图形管理器,但不清楚为什么要这样做,因为您只是在复制plt.subplots()plt.figure()方法。
请注意,使用fig.show()可能会给予后端警告(而不是错误):

UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline,
  which is a non-GUI backend, so cannot show the figure.

这是一个单独的问题,在Figure.show文档中有更详细的说明:

警告:

这并不管理GUI事件循环。因此,如果您或您的环境不管理事件循环,则该图可能只会短暂显示或根本不显示。
Figure.show的用例包括从GUI应用程序(其中有持续运行的事件循环)或从 shell (如IPython)运行此函数, shell 安装了输入挂钩,以允许交互式 shell 在图形显示和交互时接受输入。一些(但不是全部)GUI工具包将在导入时注册输入挂钩。有关详细信息,请参阅命令提示符集成。
如果你在一个没有输入钩子集成的shell中,或者在执行一个python脚本,你应该使用pyplot.showblock=True,后者负责为你启动和运行事件循环。

相关问题