使用Python,PCA对iris数据集降维2维/3维并进行2D,3D散点图绘制(包括有图例无图例,有标题Label无标题Label)

news/2024/9/22 7:08:05

这篇博客将介绍如何使用Python,PCA对iris数据集降维2,3并进行2D,3D散点图绘制(包括有图例&无图例,有标题Label&无标题Label)。
着重介绍怎么一次性添加多类型的图例到图表,通过显式获取scatter。

# 方法1
scatter = ax.scatter(x_reduced[:, 0], x_reduced[:, 1], x_reduced[:, 2], c=iris.target)
# 方法2
scatter = plt.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target, marker="d")
# 添加图例名称到图标
plt.legend(handles=scatter.legend_elements()[0],labels=sp_names,title="species", loc="upper right")

1. 效果图

对鸢尾花进行PCA降维成2维后进行绘制,Seaborn效果图如下:
在这里插入图片描述

对鸢尾花进行PCA降维成2维后进行绘制,Seaborn添加标题及散点拟合线 效果图如下:

在这里插入图片描述

对鸢尾花进行PCA降维成3维后进行绘制,Matplotlib3D效果图如下:

在这里插入图片描述
对鸢尾花进行PCA降维成3维简单绘制效果图如下:
在这里插入图片描述

对鸢尾花进行PCA降维成3维后进行绘制,添加中文标题,xyz轴描述及图例,不同类型用不同的样式mark 效果图如下:
在这里插入图片描述

2. 源码

# 使用PCA对鸢尾花特征进行降维2维/3维并绘制 2D,3D散点图(有图例&无图例,有标题Lable&无标题Lable)
# python iris_pca.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.decomposition import PCA# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseiris = datasets.load_iris()
R = np.array(iris.data)R_cov = np.cov(R, rowvar=False)iris_covmat = pd.DataFrame(data=R_cov, columns=iris.feature_names)
iris_covmat.index = iris.feature_names
eig_values, eig_vectors = np.linalg.eig(R_cov)def plot_2D_Seaborn():featureVector = eig_vectors[:, :2]featureVector_t = np.transpose(featureVector)# R is the original iris datasetR_t = np.transpose(R)newDataset_t = np.matmul(featureVector_t, R_t)newDataset = np.transpose(newDataset_t)# 可视化 绘制2D图# 鸢尾花数据创建dataframedf = pd.DataFrame(data=newDataset, columns=['PC1', 'PC2'])y = pd.Series(iris.target)y = y.replace(0, 'setosa')y = y.replace(1, 'versicolor')y = y.replace(2, 'virginica')df['Target'] = y# 绘制2维数据,fit_reg是否拟合线sns.lmplot(x='PC1', y='PC2', data=df, hue='Target', fit_reg=False, legend=True)# sns.lmplot(x='PC1', y='PC2', data=df, hue='Target', fit_reg=True, legend=True)plt.title("Seaborn鸢尾花降维2维图")  # 会被截取不全plt.show()# PCA降2维
# 无图例 & 有图例
def plot_2D_PCA_Legend():# 进行PCA降维x_reduced = PCA(n_components=2).fit_transform(iris.data)y = pd.Series(iris.target)y = y.replace(0, 'setosa')y = y.replace(1, 'versicolor')y = y.replace(2, 'virginica')fig = plt.figure()ax = fig.add_subplot()# 2D散点图无图例ax.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target, marker="d")plt.show()print(np.unique(np.array(y)).tolist())print(np.unique(iris.target).tolist())# ax.legend(np.unique(iris.target).tolist())# ax.legend(np.unique(np.array(y)).tolist(),loc='upper right')# 2D散点图有标题,label,图例plt.figure(figsize=(8, 6))sp_names = np.unique(np.array(y)).tolist()scatter = plt.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target, marker="d")plt.title('鸢尾花降维2维图')plt.xlabel("PC1", size=18)plt.ylabel("PC2", size=18)# 添加图例名称到图标plt.legend(handles=scatter.legend_elements()[0],labels=sp_names,title="species", loc="upper right")plt.show()# PCA降3维
# 无图例 & 有图例
def plot_3D_PCA_Legend():# 进行PCA降维x_reduced = PCA(n_components=3).fit_transform(iris.data)y = pd.Series(iris.target)y = y.replace(0, 'setosa')y = y.replace(1, 'versicolor')y = y.replace(2, 'virginica')fig = plt.figure()ax = Axes3D(fig)# 3D散点图无图例ax.scatter(x_reduced[:, 0], x_reduced[:, 1], x_reduced[:, 2], c=iris.target)plt.show()sp_names = np.unique(np.array(y)).tolist()fig = plt.figure()ax = Axes3D(fig)# 3D散点图有标题,label,图例scatter = ax.scatter(x_reduced[:, 0], x_reduced[:, 1], x_reduced[:, 2], c=iris.target)ax.set_title('鸢尾花降维3维图')ax.set_xlabel("PC1", size=18)ax.set_ylabel("PC2", size=18)ax.set_zlabel("PC3", size=18)# 添加图例名称到图标ax.legend(handles=scatter.legend_elements()[0],labels=sp_names,title="species", loc="upper right")plt.show()# 不同的PCA降维
def plot_3D():featureVector = eig_vectors[:, :3]featureVector_t = np.transpose(featureVector)# R is the original iris datasetR_t = np.transpose(R)newDataset_t = np.matmul(featureVector_t, R_t)newDataset = np.transpose(newDataset_t)# 构建DataFramedf = pd.DataFrame(data=newDataset, columns=['PC1', 'PC2', 'PC3'])y = pd.Series(iris.target)y = y.replace(0, 'setosa')y = y.replace(1, 'versicolor')y = y.replace(2, 'virginica')df['Target'] = y# print(df.head(5))# 根据其中一列分组df = df.groupby("Target")# print(df.groups)  # key# print(df.get_group('setosa'))  # 某个value# matplot支持的点样式及点颜色marks = ['.', '*', 's', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 'p', 'P', 'h', 'H', '+', 'x', 'X','D', 'd', '|', '_']colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']fig = plt.figure()ax = fig.add_subplot(projection='3d')ax.set_title('鸢尾花降维3维图')for i, key in enumerate(df.groups.keys()):val = df.get_group(key)ax.scatter(val["PC1"], val["PC2"], val["PC3"], c=colors[i % len(colors)], marker=marks[i % len(marks)],label=key)ax.set_xlabel('PC1')ax.set_ylabel('PC2')ax.set_zlabel('PC3')ax.legend(loc='upper right')plt.show()plot_2D_Seaborn()
plot_2D_PCA_Legend()
plot_3D_PCA_Legend()
plot_3D()

参考

  • https://datavizpyr.com/add-legend-to-scatterplot-colored-by-a-variable-with-matplotlib-in-python/
  • https://blog.csdn.net/weixin_39531761/article/details/110717013
  • https://www.jianshu.com/p/25a66dee6450

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pgtn.cn/news/17521.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

使用Python,matplotlib绘制复杂曲线,并求其交点,y=-sin(x)-x-1并求解函数的值

写这篇博客源于博友的提问&#xff0c;将介绍如何使用Python&#xff0c;matplotlib绘制复杂曲线&#xff0c;并求其交点&#xff0c;y-sin(x)-x-1并求解函数的值。 1. 效果图 ysin(x)效果图如下&#xff1a; y -x - ln(x)效果图如下&#xff1a; y-sin(x)-x-1 & y…

Java 根据Cron表达式获取近几次任务执行时间

这篇博客将介绍Java 如何根据Cron表达式获取近几次任务执行时间。实际上使用 quartz 包 CronSequenceGenerator 以及TriggerUtils.computeFireTimes 俩种方法进行时间获取&#xff1b; 1. 效果图 2. 源码 <dependency><groupId>org.quartz-scheduler</groupId…

使用Python,OpenCV对图像进行亚像素点检测,并拟合椭圆进行绘制

这篇博客将介绍如何使用Python&#xff0c;OpenCV对图像进行亚像素检测&#xff0c;并对亚像素点进行椭圆拟合绘制。 1. 效果图 原始图上绘制拟合椭圆 VS 原始图上绘制拟合椭圆及亚像素点绘制随机半径及颜色的圆 VS 灰度图上绘制亚像素点效果图如下&#xff1a; 我喜欢的颖宝…

Android控件之ImageView探究

ImageView控件是一个图片控件&#xff0c;负责显示图片。 以下模拟手机图片查看器 目录结构 main.xml布局文件 <?xml version"1.0"encoding"utf-8"?><LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"androi…

使用make_blob,KNeighborsClassifier-K近邻算法进行分类

写这篇博客源于博友的提问&#xff1a; 1. 效果图 输入 100 5 3 7 得到结果 [2] 可视化效果图如下&#xff1a;待预测点红色x展示&#xff0c; 输入 88 2 1 9 得到结果&#xff1a; [1] 可视化效果图如下&#xff1a;待预测点红色x展示&#xff0c; 2. 源码 # KNeighbo…

一生受益的三个小故事

转载于:https://www.cnblogs.com/88223100/archive/2011/02/22/three_stories.html

使用matplotlib绘制定制化饼图(图例比例标签支持中文等)

写这篇博客源于博友的提问 1. 效果图 效果图如下&#xff1a; 2. 原理 autopct‘%0.1f%%’ 自动添加百分比显示&#xff0c;格式化保留1位小数labeldistance 设置各扇形标签&#xff08;图例&#xff09;与圆心的距离&#xff08;labeldistance&#xff09;为1.1shadowTrue…

Python字母数字下划线生成田字格随机密码

写这篇博客源于博友的提问1&#xff0c;提问2 1. 效果图 10行随机密码&#xff0c;首字母不同&#xff0c;效果图如下&#xff1a; 田字格随机字符串如下&#xff1a; 2. 源码 # 生成随机密码 import randomimport numpy as np# 1. 生成随机密码,密码首字母不同 np.rando…