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

如何无需手动指定每个y轴,将DataFrame多列时间序列绘制在同一张图中

解决方法

首先需要先把示例数据里字符串格式的nan转为数值型空值,避免绘图出现异常:

import pandas as pd
import matplotlib.pyplot as plt

# 原有数据预处理逻辑不变
df1 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3.5, 0.1, 3, 'nan', 0.2], 
    '03K W':[4.2, 5.2, 2.5, 3.0, 0.6], 
    '04K W':[1.5, 2.6, 8.2, 4.2, 5.3]}) 

df1['Date'] = pd.to_datetime(df1['Date'])
df1 = df1.set_index('index')

# 新增:转换K W相关列的数值格式,自动筛选所有带K W的列
kw_cols = df1.filter(like='K W').columns
df1[kw_cols] = df1[kw_cols].apply(pd.to_numeric, errors='coerce')

方法1:直接用pandas内置plot接口(最简洁)

pandas的plot方法支持直接传入列名列表作为y轴参数,配合列筛选功能,哪怕上百个序列也不需要手动逐个指定:

df1.plot(
    x='Date',
    y=kw_cols,
    figsize=(12,6),
    xlabel='日期',
    ylabel='功率'
)
plt.legend()
plt.show()

如果你的列没有统一命名规则,也可以手动构造列名列表传入y参数即可,比逐个写plt.plot效率高很多。

方法2:循环批量绘制(适合需要自定义曲线样式的场景)

如果需要单独调整每根曲线的颜色、线型等样式,可以遍历目标列批量绘制:

for col in kw_cols:
    plt.plot(df1['Date'], df1[col], label=col)
plt.xlabel('日期')
plt.ylabel('功率')
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:36:01