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

matplotlib绘制柱状图触发TypeError仅大小1数组可转Python标量问题

问题分析

报错TypeError only size-1 arrays can be converted to Python scalars的根因是x轴坐标序列的定义错误:

  • 代码中reactions = [range(97,126)]的写法是将range迭代器作为单个元素存入列表,最终得到的是长度为1的列表,而非你预期的29个连续反应编号
  • plt.bar()要求x轴、y轴传入的序列长度必须完全一致,你当前y轴increases长度为29、x轴序列长度为1,类型和长度都不匹配,因此触发报错。

修复方法

仅需要修改reactions的定义行,将range对象转成普通列表即可:
把

reactions = [range(97,126)]

替换为

reactions = list(range(97,126))

完整可运行代码

import numpy as np
import matplotlib.pyplot as plt

numbers_ci = [1.113, 1.068, 0.999, 1.021, 1.078, 1.086, 1.024, 1.025, 1.082, 1.215, 1.069, 1.09, 1.11, 1.106, 1.02, 1.087, 1.124, 1.069, 1.004, 1.002, 1.058, 0.993, 1.024, 0.926, 1.099, 1.083, 0.995, 1.023, 1.422]

def calculate_concentration(numbers):
    concentrations = [0.3722 - (number/2.185*0.3722) for number in numbers]
    increases = [(concentration - concentrations[-1])/concentrations[-1]*100 for concentration in concentrations]
    print(f"The average absorbance numbers are:\n{numbers}")
    print(f"The concentrations of bound copper are:\n{concentrations}")
    print(f"The increases in copper binding are:\n{increases}")
    
    # 修复x轴序列定义
    reactions = list(range(97,126))
    
    plt.bar(reactions, increases)
    plt.xlabel("Reactions")
    plt.ylabel("Increase in binding capacity (%)")
    plt.title("Pure chitin")
    plt.show()

calculate_concentration(numbers_ci)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:30:01