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

Matplotlib多子图场景下ax被识别为numpy数组无法调用twinx问题

问题原因

你调用plt.subplots(13, 4)生成13行4列的子图网格时,返回的ax1是形状为(13,4)的numpy数组,数组中每个元素才是对应子图的AxesSubplot对象,twinx()是AxesSubplot类的方法,直接对numpy数组调用自然会报错。同时你原本的代码还存在对整个ax1数组读取图例的逻辑错误,需要同步调整。

修复后的代码

把twinx()创建、图例读取的逻辑放到子图遍历循环内,对每个独立的子图对象操作即可:

import matplotlib.pyplot as plt

def pumped_up_plotting(data, colname1, colname2):
    fig, ax1 = plt.subplots(13, 4, figsize=(5*4, 5*13))
    plt.subplots_adjust(hspace=0.3)

    for i in range(0, 13):
        for j in range(0,4):
            id_ = profiles[i*4+j]
            samp = data[data["profile_id"] == id_]
            # 对当前单个子图创建双Y轴
            ax2 = ax1[i,j].twinx()

            ax1[i, j].plot(samp["time"], samp[colname1], label=colname1, color="blue")
            ax2.plot(samp["time"], samp[colname2], label=colname2, color="yellow")
            ax1[i, j].set_xlabel("Time")
        
            # 读取当前子图两个轴的图例内容
            lines_1, labels_1 = ax1[i,j].get_legend_handles_labels()
            lines_2, labels_2 = ax2.get_legend_handles_labels()
        
            lines = lines_1 + lines_2
            labels = labels_1 + labels_2

            ax1[i, j].legend(lines, labels, loc=0)
    # 按需替换为plt.savefig逻辑实现批量导出
    plt.show()

pumped_up_plotting(df, "rotor", "motor_work")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:36:02