如何在同一画布的子图中分别绘制NumPy数组列表各列的折线图
分列绘制子图实现方案
实现代码
基于NumPy数组实现
import numpy as np import matplotlib.pyplot as plt # 原始得分数组 score_list = [ [0.9442483660130718, 0.957908496732026, 0.9499346405228758, 0.9475163398692809, 0.6247058823529412, 0.9475816993464052], [0.9420261437908496, 0.9638562091503268, 0.9407189542483659, 0.9415686274509802, 0.6270588235294118, 0.951111111111111], [0.9396078431372549, 0.9602614379084967, 0.9451633986928104, 0.9486928104575162, 0.6271241830065359, 0.9534640522875816], [0.944313725490196, 0.960326797385621, 0.9404575163398691, 0.9485620915032679, 0.6235947712418302, 0.9487581699346406], [0.9431372549019608, 0.9591503267973855, 0.9452287581699346, 0.9523529411764704, 0.6270588235294118, 0.9511111111111111], [0.9384967320261437, 0.9614379084967319, 0.9463398692810456, 0.9486928104575163, 0.6247058823529412, 0.9546405228758169], [0.9454901960784313, 0.9615686274509803, 0.9452287581699345, 0.9486928104575163, 0.6224183006535948, 0.9534640522875816], [0.9407189542483659, 0.9591503267973855, 0.9428104575163396, 0.9475816993464052, 0.6258823529411766, 0.9534640522875816], [0.9442483660130719, 0.9661437908496733, 0.9439869281045752, 0.9415686274509802, 0.6235947712418302, 0.9569934640522875], [0.9442483660130718, 0.9580392156862745, 0.9440522875816992, 0.9474509803921568, 0.6247712418300654, 0.951111111111111] ] score_arr = np.array(score_list) sizes = np.arange(10,110,10) # 创建2行3列子图,设置画布尺寸 fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 8)) # 把子图数组摊平为一维,方便循环遍历 axes = axes.flatten() # 逐列绘制折线到对应子图 for col_idx in range(6): current_ax = axes[col_idx] current_ax.plot(sizes, score_arr[:, col_idx], 'o--', color='blue', label=f'第{col_idx+1}列得分') current_ax.set_title(f'第{col_idx+1}列得分变化趋势') current_ax.set_xlabel('sizes') current_ax.set_ylabel('得分值') current_ax.legend() current_ax.grid(alpha=0.3) # 自动调整子图间距,避免内容重叠 plt.tight_layout() plt.show()
基于已转换DataFrame实现
如果你已经将数组转换为DataFrame,可直接使用如下简化代码:
import numpy as np import matplotlib.pyplot as plt import pandas as pd # 假设你已转换完成的DataFrame变量名为score_df score_df = pd.DataFrame(score_list) sizes = np.arange(10,110,10) fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 8)) axes = axes.flatten() for col in score_df.columns: current_ax = axes[col] current_ax.plot(sizes, score_df[col], 'o--', color='blue', label=f'第{col+1}列得分') current_ax.set_title(f'第{col+1}列得分变化趋势') current_ax.set_xlabel('sizes') current_ax.set_ylabel('得分值') current_ax.legend() current_ax.grid(alpha=0.3) plt.tight_layout() plt.show()
代码说明
- 通过
plt.subplots(2,3)直接生成2行3列的子图网格,返回的axes为二维数组,调用flatten()方法摊平后可直接按索引顺序访问每个子图 - 循环遍历6列数据,每次提取对应列的所有数值与sizes配对绘制折线,每个子图单独配置标题、坐标轴标签、图例和辅助网格
- 最后调用
plt.tight_layout()自动调整子图间距,避免标题、标签互相遮挡
内容的提问来源于stack exchange,提问作者OMOMULE KEHINDE
相关产品推荐
相关产品推荐

