【问题标题】:an array from genfromtxt is being passed as a sequence?来自 genfromtxt 的数组作为序列传递?
【发布时间】:2016-10-11 16:21:49
【问题描述】:

我在形状中有一个坐标列表及其各自的错误值:

# Graph from standard correlation, page 1
1.197   0.1838  -0.03504    0.07802 +-0.006464  +0.004201
1.290   0.2072  -0.04241    0.05380 +-0.005833  +0.008101

其中的列表示x,y,lefterror,righterror,buttomerror,toperror我将文件加载为error=np.genfromtxt("standard correlation.1",skip_header=1),最后我尝试将其绘制为

xerr=error[:,2:4]
yerr=error[:,4:]
x=error[:,0]
y=error[:,1]
plt.errorbar(x,y,xerr=xerr,yerr=yerr,fmt='')

当我尝试运行它时会大喊ValueError: setting an array element with a sequence.,我知道当您将诸如列表之类的对象传递给期望一个numpy数组对象的参数时会出现此错误,我不知道该怎么做修复这个问题,因为 np.genfromtxt 应该总是返回一个 ndarray。

感谢您的帮助。

编辑:我更改了文件以删除“+”字符,因为读取“+-”会在底部错误列中产生 NaN 值,但我仍然得到相同的错误。

【问题讨论】:

  • 打印error。还向我们展示它的shapedtype。使用genfromtxt 时,最好先看看它产生了什么,然后再尝试使用它。
  • 使用print np.shape(x),np.shape(y),np.shape(xerr),np.shape(yerr), type(datos) 我也得到(30,) (30,) (30, 2) (30, 2) <type 'numpy.ndarray'>,错误就在我上面指定的 plt.errorbar() 上

标签: python arrays numpy matplotlib errorbar


【解决方案1】:

感谢 hpaulj,我注意到误差线的形状为 (30,2),但是 plt.errobar() 预计形状为 (2,n) 的错误数组,因为 python 通常在类似操作中转置矩阵并自动避免此问题我认为它也会这样做,但我决定按以下方式更改线路:

xerr=error[:,2:4]
yerr=error[:,4:]

进入

xerr=np.transpose(error[:,2:4])
yerr=np.transpose(error[:,4:])

这使得脚本运行正常,虽然我仍然不明白为什么以前的代码给了我这样的错误,如果有人能帮我解决这个问题,我会很感激。

【讨论】:

    【解决方案2】:

    numpy 预期单个误差线的数组形状是(2, N)。因此,您需要转置您的数组error[:,2:4].T 此外,matplotlib.errorbar 了解与数据相关的这些值。如果 x 是值,(xmin, xmax) 是相应的错误,则错误栏从 x-xmin 变为 x+xmax。因此,错误栏数组中不应有负值。

    import numpy as np
    import matplotlib.pyplot as plt
    
    f = "1   0.1  0.05    0.1 0.005  0.01" + \
       " 1.197   0.1838  -0.03504    0.07802 -0.006464  0.004201 " + \
       " 1.290   0.2072  -0.04241    0.05380 -0.005833  0.008101" 
    error=np.fromstring(f, sep=" ").reshape(3,6)
    print error
    #[[ 1.        0.1       0.05      0.1       0.005     0.01    ]
    # [ 1.197     0.1838   -0.03504   0.07802  -0.006464  0.004201]
    # [ 1.29      0.2072   -0.04241   0.0538   -0.005833  0.008101]]
    
    xerr=np.abs(error[:,2:4].T)
    yerr=np.abs(error[:,4:].T)
    x=error[:,0]
    y=error[:,1]
    plt.errorbar(x,y,xerr=xerr,yerr=yerr,fmt='')
    plt.show()
    

    关于值错误,可能是+-问题引起的。

    【讨论】:

      猜你喜欢
      • 2012-06-10
      • 2020-08-09
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 2013-04-21
      • 1970-01-01
      相关资源
      最近更新 更多