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

调用自定义批量散点图函数报'tuple' object cannot be interpreted as an integer错误如何解决

错误原因

plt.subplots()方法要求前两个输入参数分别为代表子图行数、列数的整数,你直接将存储行列配置的元组number_plots作为第一个参数传入,导致无法解析触发类型错误。同时代码还存在多处其他语法/逻辑问题,统一修改方案如下:


完整修改后的代码

import matplotlib.pyplot as plt
import numpy as np

def plot_scatter_figures(chart_title,data, number_plots, selected_x, selected_y,chart_titles, color,x_labels,y_labels,color_labels,cmap):
    """Plot Scatter figures
    
    Args:
        chart_title (string): 总图表标题
        data (np.array): 存储绘图数据的numpy数组
        number_plots (tuple): 子图布局,格式为(行数, 列数)
        selected_x (list): 每个子图所用x轴对应的数组列名/索引列表
        selected_y (list): 每个子图所用y轴对应的数组列名/索引列表
        chart_titles (list): 每个子图的标题列表
        color (list): 每个子图散点颜色对应的数组列名/索引列表
        x_labels (list): 每个子图的x轴标签列表
        y_labels (list): 每个子图的y轴标签列表
        color_labels (list): 每个子图颜色条的标签列表
        cmap (list): 每个子图所用的配色方案列表
    
    Returns:
        plt: 绘制完成的图表对象
    """
    # 对number_plots拆包,分别传入行数、列数
    n_rows, n_cols = number_plots
    fig, axs = plt.subplots(n_rows, n_cols, figsize=(30,15),dpi = 80)
    fig.suptitle(chart_title,fontsize = 20)
    
    # 修正循环逻辑,遍历所有子图位置
    k = 0
    for i in range(n_rows):
        for j in range(n_cols):
            if k >= len(selected_x):
                # 子图数量多于要绘制的图数量时隐藏多余子图
                axs[i,j].set_visible(False)
                continue
            # 只调用一次scatter,存返回值给colorbar用,避免重复计算
            scatter = axs[i,j].scatter(data[selected_x[k]],data[selected_y[k]],c=data[color[k]], marker=".", s=80, cmap=cmap[k])
            plt.colorbar(scatter, ax=axs[i,j]).ax.set_title(color_labels[k],fontsize = 10)
            axs[i,j].set_title(chart_titles[k], fontsize =15)
            # 修正变量名拼写错误
            axs[i,j].set_xlabel(x_labels[k], fontsize = 15)
            axs[i,j].set_ylabel(y_labels[k], fontsize = 15)
            k += 1
    plt.tight_layout()
    return plt

关键修改点说明

  • 调用plt.subplots时对元组number_plots拆包,分别传入行数和列数,解决原类型报错
  • 修正了原循环的逻辑错误,原for i,j in number_plots、for k in len(selected_x)均为无效写法
  • 修正了变量名拼写错误:原代码中x_label、y_label与入参定义的x_labels、y_labels不匹配
  • 优化了scatter调用逻辑,避免重复计算,同时增加了多余子图的隐藏逻辑,避免索引越界
  • 增加了plt.tight_layout()自动调整子图间距,避免标题、标签重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:06:04