0
点赞
收藏
分享

微信扫一扫

Python | Matplotlib | 三维图绘图合集1

暮晨夜雪 2022-03-11 阅读 62

1 三维散点图

# 加载库
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D


# 数据设置
df=pd.DataFrame({'X': range(1,91), 'Y': np.random.randn(90)*10+range(1,91), 'Z': (np.random.randn(90)*15+range(1,91))*3 })

# 绘图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df['X'], df['Y'], df['Z'], c='grey', s=80)
ax.view_init(40, 195)
plt.show()

OUTPUT:

 2 主成分分析(PCA)结果三维图

# 加载库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA

# 图像设置
mydpi=96
plt.figure(figsize=(960/mydpi, 960/mydpi), dpi=mydpi)
 
# 数据创建
df = sns.load_dataset('iris')

# species作为变量并以不同颜色表示
df['species']=pd.Categorical(df['species'])
my_color=df['species'].cat.codes
df = df.drop('species', 1)
 
# 进行主成分分析
pca = PCA(n_components=3)
pca.fit(df)
 
# 存储数据
result=pd.DataFrame(pca.transform(df), columns=['PCA%i' % i for i in range(3)], index=df.index)
 
# 绘图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(result['PCA0'], result['PCA1'], result['PCA2'], c=my_color, cmap="Set2_r", s=60)
 
# 绘制参考轴线
xAxisLine = ((min(result['PCA0']), max(result['PCA0'])), (0, 0), (0,0))
ax.plot(xAxisLine[0], xAxisLine[1], xAxisLine[2], 'r')
yAxisLine = ((0, 0), (min(result['PCA1']), max(result['PCA1'])), (0,0))
ax.plot(yAxisLine[0], yAxisLine[1], yAxisLine[2], 'r')
zAxisLine = ((0, 0), (0,0), (min(result['PCA2']), max(result['PCA2'])))
ax.plot(zAxisLine[0], zAxisLine[1], zAxisLine[2], 'r')
 
# 命名图名与轴名
ax.set_xlabel("PCA_1")
ax.set_ylabel("PCA_2")
ax.set_zlabel("PCA_3")
ax.set_title("PCA on the iris")
plt.show()

OUTPUT:

举报

相关推荐

0 条评论