为什么会出现 'module' not callable 错误?

Why do I get the 'module' not callable error?

我是 python 的新手。我正在尝试对加速度数据进行统计分析。

我正在尝试用我的数据绘制 PCA 图。但是我收到以下错误:

File ~\OneDrive - ##\##\Pyth\untitled0.py:41 in <module>
    fig = plt.figure(figsize = (8,8))

TypeError: 'module' object is not callable

我不知道我的脚本有什么问题。也许有人知道。

这是我的 csv 的一部分(最后一列是 class (1,2,3):

-0.875,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0

这是我的代码:

import pandas as pd
import os
from sklearn.preprocessing import StandardScaler
import matplotlib as plt
from sklearn.decomposition import PCA

## find dir
os.chdir(r'C:\Users\##\OneDrive - ##\##\Pyth\HAR2')
os.getcwd()


## read csv
df = pd.read_csv('dataframe_0.csv', delimiter=',', names = ['x','y','z','target'])


features = ['x', 'y', 'z']

# Separating out the features
x = df.loc[:, features].values

# Separating out the target
y = df.loc[:,['target']].values

# Standardizing the features
x = StandardScaler().fit_transform(x)


pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2'])

finalDf = pd.concat([principalDf, df[['target']]], axis = 1)

fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,2,3) 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)

targets = [1,2,3]
colors = ['r', 'g', 'b']
for target, color in zip(targets,colors):
    indicesToKeep = finalDf['target'] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , c = color
               , s = 50)
ax.legend(targets)
ax.grid()

MatPlotLib ([MatPlotLib]: API Reference) 导入语句应该是:

import matplotlib.pyplot as plt

from matplotlib import pyplot as plt

这种情况(这使得错误更难发现)的美妙之处在于巧合。 figure name 都存在于:

  • matplotlib - 作为一个模块

  • matplotlib.pyplot - 作为函数(这是需要的)

示例:

>>> import matplotlib as mpl
>>>
>>> mpl
<module 'matplotlib' from 'e:\Work\Dev\VEnvs\py_pc064_03.09_test0\lib\site-packages\matplotlib\__init__.py'>
>>> mpl.figure
<module 'matplotlib.figure' from 'e:\Work\Dev\VEnvs\py_pc064_03.09_test0\lib\site-packages\matplotlib\figure.py'>
>>>
>>>
>>> import matplotlib.pyplot as plt
>>>
>>> plt
<module 'matplotlib.pyplot' from 'e:\Work\Dev\VEnvs\py_pc064_03.09_test0\lib\site-packages\matplotlib\pyplot.py'>
>>> plt.figure
<function figure at 0x000001C31C139D30>