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

使用numpy.arange和zip构建数据时ascii_graph绘图失败,原因为何?

使用ascii_graph时NumPy数组组装数据报错的问题与解决方法

测试Python的ascii_graph包时发现:使用numpy.arange和zip组装直方图数据会导致绘图失败,但用原生字面量组装数据可成功执行。以下是具体代码示例、报错信息及验证后的解决方法:

问题复现代码

import numpy as np
BinMid = np.arange(20) + 1 # 区间中点
BinEdge = np.arange(21) + 0.5
# 区间边界,仅用于生成直方图计数(示例代码中未展示计数生成逻辑)
nDist = np.array( # 区间计数
   [  7083,    73485,   659204,  3511238, 10859771, 22162510,
      34511661, 45891902, 55651178, 59153091, 56242073,
      48598282, 37947325, 27541907, 19356046, 13630601,
      8810979, 4262462, 1227506,   216751], dtype=np.int64 )

# 直方图数据
histData = list( zip( BinMid.astype(str) , nDist ) )

# 创建ASCII直方图绘制器
from ascii_graph import Pyasciigraph
graph = Pyasciigraph()

# 执行失败:使用zip表达式生成的histData绘图
for line in graph.graph( "Test" ,
      list( zip( BinMid.astype(str) , nDist ) ) ):
   print(line)
for line in graph.graph( "Test" , histData ): print(line)

报错信息

UnboundLocalError: local variable 'info' referenced before assignment

成功代码示例

histData = [ ('1', 7083),
             ('2', 73485),
             ('3', 659204),
             ('4', 3511238),
             ('5', 10859771),
             ('6', 22162510),
             ('7', 34511661),
             ('8', 45891902),
             ('9', 55651178),
             ('10', 59153091),
             ('11', 56242073),
             ('12', 48598282),
             ('13', 37947325),
             ('14', 27541907),
             ('15', 19356046),
             ('16', 13630601),
             ('17', 8810979),
             ('18', 4262462),
             ('19', 1227506),
             ('20', 216751) ]
for line in graph.graph( "Test" , histData ): print(line)

可行解决方法

基于Nick ODell的回复,使用原生Python列表生成标签可解决该问题,示例代码如下:

import numpy as np
BinMidStr = [ str(i+1) for i in range(20) ] # 区间标签
nDist = np.array( # 区间计数
   [  7083,    73485,   659204,  3511238, 10859771, 22162510,
      34511661, 45891902, 55651178, 59153091, 56242073,
      48598282, 37947325, 27541907, 19356046, 13630601,
      8810979, 4262462, 1227506,   216751], dtype=np.int64 )

# 直方图数据
histData = list( zip( BinMidStr , nDist ) )

# 创建ASCII直方图绘制器
from ascii_graph import Pyasciigraph
graph = Pyasciigraph()

# 绘图代码示例1
for line in graph.graph( "Test" ,
                          list( zip( BinMidStr , nDist ) ) ):
   print(line)

注意事项:

  • np.array_str()无法生成单个原生字符串标签,它会返回整个数组的字符串表示;
  • 将NumPy数组转换为原生Python数组可使用MyNParray.tolist()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:50:10