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

使用twinx绘制双轴图报错:'PlotAccessor'对象无'twinx'属性

问题解决:AttributeError: 'PlotAccessor' object has no attribute 'twinx'

错误原因

你代码里的dataframe_raw[item].plot是Pandas的PlotAccessor工具对象,并非Matplotlib的坐标轴(Axes)实例,而twinx()是Axes对象才有的方法,因此会触发报错。

两种修复方案

方案一:修正plot调用,直接获取Axes对象

import matplotlib.pyplot as plt

ListOfVariables = ['Volumetric Flow Meter 1',  'Volumetric Flow Meter 2',  'Pump Speed (RPM)', 'Pump Torque',   'Ambient Temperature',  'Horse Power',  'Pump Efficiency']

for item in ListOfVariables:
    # 调用plot()方法,返回Axes实例
    first_axis = dataframe_raw[item].plot()
    # 基于第一个轴创建双Y轴
    second_axis = first_axis.twinx()
    # 在双轴上绘制故障数据
    second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
    plt.title(item)
    plt.show()

方案二:显式创建画布与坐标轴(更灵活可控)

这种方式便于后续调整坐标轴标签、样式等细节:

import matplotlib.pyplot as plt

ListOfVariables = ['Volumetric Flow Meter 1',  'Volumetric Flow Meter 2',  'Pump Speed (RPM)', 'Pump Torque',   'Ambient Temperature',  'Horse Power',  'Pump Efficiency']

for item in ListOfVariables:
    # 初始化画布和第一个坐标轴
    fig, first_axis = plt.subplots()
    # 绘制第一个变量
    first_axis.plot(dataframe_raw[item], color='cornflowerblue')
    first_axis.set_ylabel(item)
    
    # 创建双Y轴
    second_axis = first_axis.twinx()
    # 绘制故障状态数据
    second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
    second_axis.set_ylabel('PUMP FAILURE (1 or 0)')
    
    plt.title(item)
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:30:36