如何修复:模块'matplotlib'没有属性'plot'

1,394 阅读1分钟

在使用matplotlib时,你可能遇到的一个错误是:

AttributeError: module 'matplotlib' has no attribute 'plot'

这个错误通常发生在你使用下面的代码导入matplotlib时:

import matplotlib as plt

相反,你应该使用:

import matplotlib.pyplot as plt

下面的例子显示了如何在实践中解决这个错误。

如何重现该错误

假设我们试图用下面的代码在matplotlib中创建一个线图:

import matplotlib as plt

#define data
x = [1, 2, 3, 4, 5, 6]
y = [3, 7, 14, 19, 15, 11]

#create line plot
plt.plot(x, y)

#show line plot
plt.show()

AttributeError: module 'matplotlib' has no attribute 'plot' 

我们收到一个错误,因为我们使用了错误的代码行来导入matplotlib库。

如何修复该错误

要解决这个错误,我们只需要使用正确的代码来导入matplotlib库:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4, 5, 6]
y = [3, 7, 14, 19, 15, 11]

#create line plot
plt.plot(x, y)

#show line plot
plt.show()

请注意,我们能够成功地创建折线图而没有收到任何错误,因为我们使用了正确的代码行来导入matplotlib库。

其他资源

下面的教程解释了如何修复 Python 中的其他常见错误:

如何修复:没有名为matplotlib的模块
如何修复:没有名为pandas的模块
如何修复:没有名为numpy的模块