Python绘制PCA图报'module' object is not callable错误求解
报错根因
你遇到的TypeError: 'module' object is not callable来自两处代码问题:
- 第一处是matplotlib导入写法错误:你用了
import matplotlib as plt,此时plt指向的是matplotlib顶层模块,而figure()是matplotlib.pyplot子模块下的函数,直接调用plt.figure()相当于尝试把模块当函数执行,必然触发类型错误。 - 第二处是隐藏的子图参数错误:你写的
fig.add_subplot(1,2,3)不符合参数规则,该方法前两个参数是子图网格的行数、列数,第三个参数是当前选中的子图序号,序号最大值不能超过行数×列数,1行2列的网格最多只有2个子图位置,传入3会在你修复导入问题后触发索引越界错误。
修复步骤
- 替换错误的matplotlib导入语句,采用matplotlib的标准导入写法:
import matplotlib.pyplot as plt - 修改子图创建参数,你只需要单张画布展示2主成分的PCA结果,用1行1列的网格即可,对应代码改为:
ax = fig.add_subplot(1,1,1) - (可选)在代码最后加上
plt.show(),确保脚本运行时可以正常弹出绘图窗口。
修复后的完整可运行代码
import pandas as pd import os from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from sklearn.decomposition import PCA ## 切换工作目录 os.chdir(r'C:\Users\##\OneDrive - ##\##\Pyth\HAR2') os.getcwd() ## 读取csv数据 df = pd.read_csv('dataframe_0.csv', delimiter=',', names = ['x','y','z','target']) features = ['x', 'y', 'z'] # 提取特征列 x = df.loc[:, features].values # 提取标签列 y = df.loc[:,['target']].values # 特征标准化 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,1,1) 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() plt.show()
内容的提问来源于stack exchange,提问作者SimonDL
相关产品推荐
相关产品推荐

