Python "'module' object is not callable"

6

我正在尝试制作一个图表:

from matplotlib import *
import sys
from pylab import *

f = figure ( figsize =(7,7) )

但是当我尝试执行它时,我会遇到这个错误:

  File "mratio.py", line 24, in <module>
    f = figure( figsize=(7,7) )
TypeError: 'module' object is not callable

我之前已经运行过类似的脚本,并且我认为我已经导入了所有相关的模块。


你是否使用其他变量名称遮蔽了 figure - tacaswell
运行 import pylab; print pylab.__file__ 并给我们结果。 - Winston Ewert
/home/apps/fas/Langs/Python/2.7.2/lib/python2.7/site-packages/matplotlib/pylab.pyc - ylangylang
我看到你的错误在第24行,你运行代码片段时是否真的遇到了这个错误,还是出现了更长的错误信息? - Winston Ewert
我还没有尝试过仅运行这个片段。但是我发现,一旦我导入了一堆看似不相关的模块,它就又开始工作了。 - ylangylang
显示剩余4条评论
6个回答

12

figure 是由 matplotlib 提供的一个模块。

你可以在 Matplotlib 文档 中了解更多信息。

我认为你需要的是 matplotlib.figure.Figure(类而不是模块)。

这里有文档

from matplotlib import *
import sys
from pylab import *

f = figure.Figure( figsize =(7,7) )
或者
from matplotlib import figure
f = figure.Figure( figsize =(7,7) )
或者
from matplotlib.figure import Figure
f = Figure( figsize =(7,7) )

或者让pylab在不与matplotlib冲突的情况下正常工作:

from matplotlib import *
import sys
import pylab as pl

f = pl.figure( figsize =(7,7) )

2
但是figure应该是来自pylab的一个函数,所以这仍然可以工作。 - Winston Ewert
@WinstonEwert 我已经添加了另一种解决方案,允许 pylab 导入图形而不会与 matplotlib 冲突。 - Ewan
1
但这并不能解释为什么pylab中的figure没有替换matplotlib中的figure。它本应该替换的。 - Winston Ewert
我也在想同样的问题。我之前曾经绘制过图形,但没有调用“figure.Figure”。 - ylangylang
使用这段代码片段在Python v3.5上可以正常工作,但是如果我改变导入的顺序,在matplotlib之前加载pylab,就会出现错误。因此,顺序很重要。最好像@Ewan建议的那样明确指定pl.figure以避免这种情况。 - Damo
请查看 @minion_1 的 2020 解决方案。 - questionto42

3

你需要做的是:

matplotlib.figure.Figure

在这里,

matplotlib.figure is a package (module), and `Figure` is the method

参考这里

因此,您需要像这样调用它:

f = figure.Figure(figsize=(7,7))

@minion_1的解决方案是实际解决方案,这里是2013年的解决方案。 - questionto42

3

与其

from matplotlib import *

使用

import matplotlib.pyplot as plt

这已经被 minion_1 提到过了。但你提供了一个清晰格式的建议来进行更改。 - questionto42

2
为了避免未来与matplotlib.pyplot相关的错误,请尝试执行以下操作: import matplotlib.pyplot as plt
如果您使用Jupyter笔记本并使用:%matplotlib inline,请确保“%matplotlib inline”跟随“import matplotlib.pyplot as plt”。
Karthikr的答案有效,但可能无法消除与pyplot模块相关的其他代码行中的错误。
编码愉快!

0
对于Jupyter笔记本,我通过导入matplotlib.pyplot来解决这个问题。
import matplotlib.pyplot as plt
%matplotlib notebook

现在使用f = plt.figure()可以制作图表了。

0

错误的库:

import matplotlib as plt

plt.figure(figsize=(7, 7))

类型错误:'模块' 对象不可调用

但是

正确的库:

import matplotlib.pyplot as plt

plt.figure(figsize=(7, 7))

上面的代码对于同样的错误对我有用。


你的回答可以通过提供更多支持性信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心中找到有关如何撰写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接