来自genfromtxt的数组作为序列传递?

时间:2016-10-11 16:21:49

标签: python arrays numpy matplotlib errorbar

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

# 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值,但我仍然会收到相同的错误。

2 个答案:

答案 0 :(得分:0)

感谢hpaulj我注意到错误栏' shape是(30,2),但plt.errobar()期望形状(2,n)中的错误arrarys,因为python通常在类似的操作中转换矩阵并自动避免这个问题我认为它也会这样做,但我决定以下列方式更改行:

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

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

这使脚本运行正常,虽然我仍然不明白为什么前面的代码给了我这样的错误,如果有人能帮我清楚,我会很感激。

答案 1 :(得分:0)

对于单个错误栏,数组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()

关于价值错误,可能是由+-问题造成的。