【问题标题】:Matplotlib mpl.figure.Figure() fails, whereas fig,ax=plt.subplots() succeedsMatplotlib mpl.figure.Figure() 失败,而 fig,ax=plt.subplots() 成功
【发布时间】:2020-03-09 13:12:45
【问题描述】:

我想使用 matplotlib 2.1.2 在不使用 pyplot 的情况下创建一个 matplotlibFigure。 这会失败并出现属性错误。

import matplotlib as mpl
fig = mpl.figure.Figure()

AttributeError: 模块 'matplotlib' 没有属性 'figure'

但是,如果有任何后端的导入,在图调用之前,它会成功。 或者,在 Jupyter 中,如果有 %matplotlib inline%matplotlib widget,它也会成功。

import matplotlib as mpl
import matplotlib.backends.backend_tkagg as tkagg
fig = mpl.figure.Figure()

后端的导入如何在matplotlib中添加figure? 这是预期的行为吗?

pyplot接口好像没有这样的依赖:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

无论后端是否导入,总是成功。

【问题讨论】:

    标签: python matplotlib matlab-figure


    【解决方案1】:

    这只是直接导入的问题。

    import matplotlib.figure
    fig = matplotlib.figure.Figure()
    

    按预期工作,即确保在使用子模块之前导入它们。

    【讨论】:

    • 那么导入后端真的没有什么关系吗?后端代码可能会导入图形子模块并使其可用?子模块在使用之前总是需要显式导入,或者这仅适用于 matplotlib 和某些库。
    • 正确。任何子模块都是模块,需要导入模块。不过,包的 __init__.py 通常会为您做这样的事情,因此您可能已经看到了不需要这样做的情况。 matplotlib 的 __init__.py 不适用于 figure 子模块,因此您需要自己做。
    • 这很有帮助,谢谢。在我自己的模块中,我总是在 init 中导入子模块,我只是假设所有库都是这样做的。但你的评论很清楚。
    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多