[英]Python: Trying to plot error bars on a graph gives “ValueError: err must be [ scalar | N, Nx1 or 2xN array-like ]”
當我嘗試在圖形上繪制誤差線時出現以下問題。
import numpy as np
import sys
import matplotlib.pyplot as plt
col1 = []
col2 = []
col3 = []
while True:
try:
N = input('Please enter the full name of your numbers text file with
its file format (e.g "Numbers.txt"): ')
with open(N, 'r') as f:
for line in f:
first, second, third = line.split()
col1.append(first)
col2.append(second)
col3.append(third)
except IOError:
sys.exit('Error: Data file is invalid! Please ensure your file
exists. ')
except ValueError:
sys.exit('Error: Data file is invalid! Please ensure your file
contains just numbers, as well as enough of them with none missing. ')
else:
break
x = np.array(col1)
y = np.array(col2)
e = np.array(col3)
N = 1
p = 0
while N <= len(col1):
p = p + 1/(float(col3[N-1]))**2
N = N+1
N = 1
q = 0
while N <= len(col1):
q = q + float(col1[N-1])/(float(col3[N-1]))**2
N = N+1
N = 1
r = 0
while N <= len(col1):
r = r + float(col2[N-1])/(float(col3[N-1]))**2
N = N+1
N = 1
s = 0
while N <= len(col1):
s = s + (float(col1[N-1]))**2/(float(col3[N-1]))**2
N=N+1
N = 1
t = 0
while N <= len(col1):
t = t + (float(col1[N-1])*float(col2[N-1]))/(float(col3[N-1]))**2
N = N+1
delta = (p*s)-(q**2)
a = ((r*s)-(q*t))/delta
b = ((p*t)-(q*r))/delta
print('a is equal to: ' + str(a))
print('b is equal to: ' + str(b))
sigma_a = float(s/delta)**0.5
sigma_b = float(p/delta)**0.5
print('Error in a (Sigma_a) is equal to: ' + str(sigma_a))
print('Error in b (Sigma_b) is equal to: ' + str(sigma_b))
best_y = []
best_x = col1
N = 0
while N <= len(col1)-1:
Y = a + ((b)*(float(col1[N])))
best_y.append(Y)
N = N + 1
Y = 0
plt.plot(x, y, 'ro', best_x, best_y)
plt.errorbar(x, y, yerr=e, fmt='-o')
plt.title('Graph to show relationship between given values of x and y')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
python提供的輸出是這樣的:
"ValueError: err must be [ scalar | N, Nx1 or 2xN array-like ]"
似乎是什么問題?
順便說一句,用於提供數字的文件是txt文件,它是:
-2 2.1 -0.365635756
0 2.4 0.347433737
2 2.5 0.263774619
4 3.5 -0.244930974
6 4.2 -0.004564913
為這篇文章中的大量代碼表示歉意,但我覺得我應該包括任何可能隱藏問題的內容(對於python來說還是很新的)。
非常感謝,
盧克。
您沒有將文件中的字符串值轉換為浮點數。 這就是為什么matplotlib
錯誤的原因。 當您通過np.array()
將col1
, col2
和col3
轉換為數組時,它不會將字符串值轉換為浮點數,它只會創建字符串數組(您可以通過檢查x
, y
或e
來看到這一點:
In[1]: x
Out[1]:
array(['-2', '0', '2', '4', '6'],
dtype='<U2')
dtype='<U2'
表示元素是unicode字符串。
修復代碼的最快方法是在讀取值時將值顯式轉換為float,將其添加到列列表中,如下所示:
while True:
try:
N = input('Please enter the full name of your numbers text file with
its file format (e.g "Numbers.txt"): ')
with open(N, 'r') as f:
for line in f:
first, second, third = line.split()
col1.append(float(first))
col2.append(float(second))
col3.append(float(third))
更好的解決方法是使用Python標准庫csv
模塊來處理數據文件的讀取和解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.