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

使用Pandas绘制双轴折线图并遍历DataFrame分析数值变量与泵故障的关联

问题:遍历DataFrame数值列,绘制双轴折线图关联泵故障状态

我有一个包含泵运行数据和故障标签的DataFrame,结构如下:

import pandas as pd
import matplotlib.pyplot as plt

data = {'TIMEFRAME':['9/12/2014 17:52', '10/12/2014 5:02', '10/12/2014 8:04'], 
        'Volumetric Flow Meter 1':[0.82, 0.88, 0.9], 
        'Pump Speed (RPM)':[2.5,2.7,3.01], 
        'Data Source':['raw data','raw data','raw data'], 
        'PUMP FAILURE (1 or 0)':[0,0,1]}
df = pd.DataFrame(data)

对应的表格内容:

TIMEFRAMEVolumetric Flow Meter 1Pump Speed (RPM)Data SourcePUMP FAILURE (1 or 0)
9/12/2014 17:520.822.5raw data0
10/12/2014 5:020.882.7raw data0
10/12/2014 8:040.903.01raw data1

我的需求是:遍历所有数值列,为每个数值列绘制双轴折线图——左Y轴显示该数值列的数据,右Y轴显示PUMP FAILURE (1 or 0)的故障状态,两者共享X轴(时间),以此观察数值变化和故障的关联趋势。

我尝试了以下代码,但无法生成预期的图表:

ListOfVariables=[df["Pump Speed (RPM)"],df["Volumetric Flow Meter 1"]]
for item in ListOfVariables:
    first_axis = df[item].plot #Looping through every item in the dataframe.
    second_axis = first_axis.twinx() #The Twinx function is used to ensure we share the X-Axis for both plots
    second_axis.plot(df['PUMP FAILURE (1 or 0)'], color='teal')
    plt.title(item)
    plt.show()

希望能得到帮助修正代码,实现预期功能。


解决方案

你的代码有几个关键问题需要修正:

  1. ListOfVariables里存储的是Series对象,而不是列名,直接用df[item]会引发索引错误;
  2. df[item].plot只是引用了plot方法,没有实际调用绘图;
  3. 没有正确关联X轴的时间数据,导致图表的X轴不是时间维度。

下面是修正后的完整代码,我会一步步解释:

import pandas as pd
import matplotlib.pyplot as plt

# 先确保TIMEFRAME是时间类型,这样X轴会按时间顺序显示
df['TIMEFRAME'] = pd.to_datetime(df['TIMEFRAME'])

# 提取所有数值列(排除非数值的TIMEFRAME和Data Source)
numeric_cols = df.select_dtypes(include=['float64', 'int64']).columns
# 排除故障标签列,因为我们要把它作为右轴
numeric_cols = numeric_cols.drop('PUMP FAILURE (1 or 0)')

# 遍历每个数值列
for col in numeric_cols:
    # 创建画布和主轴(左Y轴)
    fig, ax1 = plt.subplots(figsize=(8, 4))
    
    # 左轴绘制当前数值列,X轴用TIMEFRAME
    ax1.plot(df['TIMEFRAME'], df[col], color='tab:blue', marker='o')
    ax1.set_xlabel('Time')
    ax1.set_ylabel(col, color='tab:blue')
    ax1.tick_params(axis='y', labelcolor='tab:blue')
    
    # 创建双轴(右Y轴)
    ax2 = ax1.twinx()
    # 右轴绘制故障状态
    ax2.plot(df['TIMEFRAME'], df['PUMP FAILURE (1 or 0)'], color='tab:teal', marker='s', linestyle='--')
    ax2.set_ylabel('Pump Failure (1=Fail)', color='tab:teal')
    ax2.tick_params(axis='y', labelcolor='tab:teal')
    
    # 设置标题,添加图例让图表更清晰
    plt.title(f'{col} vs Pump Failure Status')
    fig.tight_layout()  # 自动调整布局,避免标签重叠
    plt.show()

关键改进点:

  • 先把TIMEFRAME转为时间类型,确保X轴按时间顺序排列,符合数据的时间逻辑;
  • 用select_dtypes自动提取数值列,避免手动列名的硬编码,扩展性更好;
  • 明确创建画布和轴对象,而不是依赖pandas的plot默认行为,更灵活可控;
  • 添加了标记点、线型、颜色区分,以及轴标签颜色匹配,让图表可读性更强;
  • 使用fig.tight_layout()避免标签被截断。

运行这段代码后,你会得到两个独立的双轴折线图:一个是泵转速和故障状态的关联图,另一个是体积流量和故障状态的关联图,清晰展示每个数值变量随时间的变化和故障发生的对应关系。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:02:44