I am kind of new to python. I am trying to do a statistical analyse on acceleration data.
I am trying to do a PCA plot with my data. But I get the following error:
File ~\OneDrive - ##\##\Pyth\untitled0.py:41 in <module>
fig = plt.figure(figsize = (8,8))
TypeError: 'module' object is not callable
I do not know what is wrong with my script. Maybe someone knows.
This is part of my csv (the last column is a 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
And this is my code:
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()
CodePudding user response:
The MatPlotLib ([MatPlotLib]: API Reference) import statement should be:
import matplotlib.pyplot as plt
or
from matplotlib import pyplot as plt
The beauty of this situation (which makes the error harder to find) is a coincidence. figure name exists under both:
matplotlib - as a module
matplotlib.pyplot - as a function (this is the needed one)
Example:
>>> 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>