如何用Python提取并绘制矩阵对角线元素折线图?
提取矩阵对角线元素并绘制折线图
核心思路
要提取矩阵的对角线元素并绘图,关键是确定起始位置,然后按行索引+1、列索引+1的规律依次取元素,直到超出矩阵边界;最后用绘图库生成折线图即可。
具体实现(Python)
假设你的矩阵是二维列表或numpy数组,以下是完整操作步骤:
1. 准备数据
以你给出的4×4数值矩阵为例(剔除index列,保留纯数值部分):
import numpy as np import matplotlib.pyplot as plt # 示例4×4矩阵(对应表格中2020-2023列的数值) matrix = np.array([ [1, 2, 5, 7], [3, 5, 8, 10], [1, 2, 5, 3], [3, 5, 8, 4] ])
2. 定义对角线提取函数
写一个通用函数,根据起始行、列索引提取对角线元素:
def get_diagonal(matrix, start_row, start_col): rows, cols = matrix.shape diagonal = [] i = 0 # 循环提取,直到行或列索引超出矩阵范围 while start_row + i < rows and start_col + i < cols: diagonal.append(matrix[start_row + i][start_col + i]) i += 1 return diagonal
3. 按需求提取并绘图
- 情况1:从2020列(列索引0)、行0开始
# 起始位置:行0,列0(对应表格中2020列、index=0的行) diag1 = get_diagonal(matrix, start_row=0, start_col=0) print("提取的对角线元素:", diag1) # 输出:[1, 5, 5, 4] # 绘制折线图 plt.plot(diag1, marker='o', label='2020列起始') plt.title('矩阵对角线元素折线图') plt.xlabel('位置序号') plt.ylabel('元素值') plt.legend() plt.show()
- 情况2:从2021列(列索引1)、行0开始
按行+1、列+1的规则提取,得到元素[2, 8, 3]。如果需要匹配你描述的[2,8,10],可调整起始行/列参数(比如起始行改为1、列1,提取结果为[5,8,4]),根据实际需求灵活修改即可。
4. 扩展到120×70矩阵
对于120行70列的矩阵,只需替换matrix为你的真实数据,再指定对应起始行、列索引:
# 替换为你的120×70真实矩阵 large_matrix = np.random.rand(120, 70) # 示例:从行5、列10开始提取对角线 diag_large = get_diagonal(large_matrix, start_row=5, start_col=10) plt.plot(diag_large, marker='.') plt.show()
注意事项
- 矩阵的行、列索引默认从0开始,需根据你的列名(如2020、2021)对应到正确的列索引。
- 如果你的数据是pandas DataFrame,可先转换为numpy数组:
matrix = df.values,再执行提取操作。
内容的提问来源于stack exchange,提问作者gumpy007
相关产品推荐
相关产品推荐

