要读取 Excel 文档数据并制作散点矩阵图,需要使用 Python 中的 pandas 和 matplotlib 库。

首先,使用 pandas 库中的 read_excel 函数读取 Excel 文档中的数据:

import pandas as pd

df = pd.read_excel('data.xlsx')

其中,'data.xlsx' 是 Excel 文档的文件名。读取后,可以使用 head() 函数查看前几行数据:

print(df.head())

接下来,使用 matplotlib 库中的 scatter 函数绘制散点矩阵图。散点矩阵图需要将每个变量两两之间进行比较,因此需要使用两个 for 循环遍历所有变量的组合。

import matplotlib.pyplot as plt

variables = list(df.columns)  # 获取所有变量的名称
n = len(variables)

fig, ax = plt.subplots(n, n, figsize=(10, 10))  # 创建画布和子图

for i in range(n):
    for j in range(n):
        ax[i, j].scatter(df[variables[j]], df[variables[i]])  # 绘制散点图
        ax[i, j].set_xlabel(variables[j])  # 设置x轴标签
        ax[i, j].set_ylabel(variables[i])  # 设置y轴标签

plt.show()  # 显示图形

其中,figsize 参数指定画布的大小。通过两个 for 循环遍历所有变量的组合,使用 scatter 函数绘制散点图,并设置 x 轴和 y 轴的标签。最后使用 show() 函数显示图形。

完整代码如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel('data.xlsx')
print(df.head())

variables = list(df.columns)
n = len(variables)

fig, ax = plt.subplots(n, n, figsize=(10, 10))

for i in range(n):
    for j in range(n):
        ax[i, j].scatter(df[variables[j]], df[variables[i]])
        ax[i, j].set_xlabel(variables[j])
        ax[i, j].set_ylabel(variables[i])

plt.show()
Python 散点矩阵图绘制:从 Excel 数据读取

原文地址: https://www.cveoy.top/t/topic/f0hX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录