Jas*_*ang 5 python matplotlib figure
有关于使用matplotlib.pyplotmatplotlib 3.5.1 的错误报告,所以我尝试使用它matplotlib.figure.Figure来绘制图形并且它工作正常。
Figure当我无法调用时,如何在 matplotlib 中查看图形plt.show?调用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()
Run Code Online (Sandbox Code Playgroud)
显示此问题的演示代码:
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
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚您的最终目标是否是:
fig.show()fig.show()专门用于原始Figure()对象1.如果你只是想使用fig.show()
然后第一个代码块可以通过替换plt.subplots()为来正常工作:plt.show()fig.show()
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
Run Code Online (Sandbox Code Playgroud)
2. 如果你特别想使用原始Figure()对象
那么问题是它缺少一个图形管理器:
如果图形不是使用创建的
pyplot.figure,它将缺少 aFigureManagerBase,并且此方法将引发 anAttributeError。
这意味着您需要手动创建图形管理器,但不清楚为什么要这样做,因为您只是复制plt.subplots()orplt.figure()方法。
请注意,使用fig.show()可能会给出后端警告(而不是错误):
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
Run Code Online (Sandbox Code Playgroud)
这是一个单独的问题,在文档中有更详细的解释Figure.show:
警告:
这不管理 GUI 事件循环。因此,如果您或您的环境不管理事件循环,则该图可能仅短暂显示或根本不显示。
用例包括
Figure.show从 GUI 应用程序(其中持续运行事件循环)或从 shell(如 IPython)运行此程序,安装输入挂钩以允许交互式 shell 在图形显示和交互的同时接受输入。一些(但不是全部)GUI 工具包将在导入时注册输入挂钩。有关更多详细信息,请参阅命令提示符集成。如果您使用的 shell 没有输入挂钩集成或执行 python 脚本,则应该使用
pyplot.showwithblock=True来代替,它会为您启动和运行事件循环。
| 归档时间: |
|
| 查看次数: |
1012 次 |
| 最近记录: |