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

如何批量绘制DataFrame列数据并自动将列名设为Matplotlib图表标题?

如何批量绘制DataFrame列数据并自动将列名设为Matplotlib图表标题?

没问题,这个需求完全能实现!而且用循环批量处理就搞定了,针对你有20多列的场景,我给你两种实用的方案:

方案一:每列单独生成一个图表窗口

这种方式适合需要单独查看每列数据趋势的场景,每个图表会在独立窗口弹出:

import pandas as pd
import matplotlib.pyplot as plt

begin_date = '2019-01-01'
    
df = pd.DataFrame ({
    "date": pd.date_range(begin_date, periods=5),
    "John": [42, 40, 47, 49, 51],
    "Ana": [50, 43, 41, 46,47],
    "Goku": [55, 58, 62, 64, 69],                  
})

# 先把date列设为索引,让x轴显示日期更直观(也可以不设,后面绘图时指定x轴)
df.set_index('date', inplace=True)

# 遍历所有列名,直接用列名做标题
for column_name in df.columns:
    # 创建新画布,避免所有图重叠在一个窗口
    plt.figure()
    # 绘制当前列的折线图
    plt.plot(df[column_name])
    # 用f-string直接把列名插入标题,完美实现你的需求
    plt.title(f"Name of graph: {column_name}")
    # 可以添加坐标轴标签让图表更清晰
    plt.xlabel("Date")
    plt.ylabel("Value")
    # 显示当前图表
    plt.show()

核心逻辑就是用df.columns获取所有列名,循环时把每个column_name直接塞进标题里,完全不用手动写每个名字,20多列也能一键处理。


方案二:所有列的图表放在同一画布的子图中

如果需要同时对比所有列的趋势,这种子图布局会更方便:

import pandas as pd
import matplotlib.pyplot as plt

begin_date = '2019-01-01'
    
df = pd.DataFrame ({
    "date": pd.date_range(begin_date, periods=5),
    "John": [42, 40, 47, 49, 51],
    "Ana": [50, 43, 41, 46,47],
    "Goku": [55, 58, 62, 64, 69],                  
})

df.set_index('date', inplace=True)

# 计算子图的行列数,这里设置每行3个图表,行数自动向上取整
total_cols = len(df.columns)
cols_per_row = 3
rows = (total_cols + cols_per_row - 1) // cols_per_row  # 向上取整的小技巧

# 创建画布和子图集合
fig, axes = plt.subplots(rows, cols_per_row, figsize=(15, rows*5))
# 把子图数组展平成一维,方便循环遍历
axes = axes.flatten()

# 遍历列名和对应的子图
for idx, column_name in enumerate(df.columns):
    # 在对应子图上绘图
    axes[idx].plot(df[column_name])
    axes[idx].set_title(f"Name of graph: {column_name}")
    axes[idx].set_xlabel("Date")
    axes[idx].set_ylabel("Value")

# 如果列数不是每行列数的整数倍,隐藏多余的空白子图
for j in range(idx+1, len(axes)):
    axes[j].axis('off')

# 自动调整子图间距,避免标题和标签重叠
plt.tight_layout()
plt.show()

这个方案会自动根据你列的数量调整子图布局,不管是20列还是更多,都能整齐排列,每个子图的标题依然自动用列名填充。

另外,如果不想把date列设为索引,也可以在绘图时直接指定x轴:plt.plot(df['date'], df[column_name]),效果是一样的。

备注:内容来源于stack exchange,提问作者Daniel M M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:38:09