You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Pandas为855行2列数据每10行生成折线图

实现按每10行生成折线图的方案

核心思路

把855行数据按每10行划分为一组,最后一组取剩余的5行,总共得到86组。每组单独绘制包含A、B两列的折线图,所有图表垂直排列展示。

完整代码实现

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 生成示例DataFrame
df = pd.DataFrame(np.random.randint(0,100,size=(855, 2)), columns=list('AB'))

# 计算分组总数(向上取整)
total_groups = (len(df) + 9) // 10

# 创建画布与子图,设置合适尺寸保证图表清晰
fig, axes = plt.subplots(nrows=total_groups, ncols=1, figsize=(8, 3*total_groups))

# 循环处理每组数据
for i in range(total_groups):
    # 确定当前组的行索引范围
    start_idx = i * 10
    end_idx = min(start_idx + 10, len(df))
    group_data = df.iloc[start_idx:end_idx]
    
    # 获取当前子图对象(兼容单组情况)
    ax = axes[i] if total_groups > 1 else axes
    
    # 绘制A、B列折线,用不同标记和线型区分
    group_data['A'].plot(ax=ax, label='A', marker='o', linestyle='-')
    group_data['B'].plot(ax=ax, label='B', marker='s', linestyle='--')
    
    # 设置子图标题与坐标轴信息
    ax.set_title(f'第{i+1}组数据(行{start_idx}至{end_idx-1})')
    ax.set_xlabel('行索引')
    ax.set_ylabel('数值')
    ax.legend()
    ax.grid(True, alpha=0.3)

# 自动调整子图间距,避免元素重叠
plt.tight_layout()
# 展示所有图表
plt.show()

代码说明

  • 分组逻辑:用(len(df) + 9) // 10实现向上取整,确保最后不足10行的部分单独成组。
  • 布局设置:通过subplots一次性创建86个垂直排列的子图,设置figsize让高度足够容纳所有图表。
  • 绘图细节:给折线添加标记点和不同线型,方便区分A、B列;添加网格、图例和标题提升可读性;tight_layout()自动调整间距,避免标题与坐标轴重叠。

内容的提问来源于stack exchange,提问作者darkuss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:42:23