簡體   English   中英

Python Matplotlib:不對稱誤差線 ValueError

[英]Python Matplotlib: Asymmetric Error Bars ValueError

我正在嘗試為許多來源繪制列密度“nh”圖。 每個來源由一個鍵值表示。 而且我有多個字典將該鍵與某個值匹配。 例如:

print(nh_noUL_val, '\n')
print(noUL_colors, '\n')
print(asymetric_error,'\n')

這給了我的數據:

{2: 3.3e+21, 7: 7e+20, 29: 2e+22, 203: 8.5e+21, 226: 2.1e+21, 231: 6e+19, 259: 4.2e+21, 307: 1.8e+20, 320: 2.6e+21, 366: 4.4e+22, 374: 6e+21, 1143: 3e+22} 

{2: 'black', 7: 'green', 29: 'red', 203: 'blue', 226: 'blue', 231: 'blue', 259: 'blue', 307: 'green', 320: 'green', 366: 'blue', 374: 'red', 1143: 'red'} 

{2: [4e+20, 4e+20], 7: [7e+20, 3.6e+21], 29: [2e+22, 3.3e+22], 203: [8.5e+21, 2.47e+22], 226: [2.1e+21, 2.17e+22], 231: [6e+19, 9.76e+21], 259: [4.2e+21, 1.9899999999999997e+22], 307: [1.8e+20, 4.65e+21], 320: [2.6e+21, 1.2900000000000001e+22], 366: [4.4e+22, 1.4800000000000001e+23], 374: [6e+21, 3.1e+22], 1143: [3e+22, 4e+22]} 

使用這些數據,我嘗試將每個源繪制為帶有各自顏色、值和不對稱誤差的彩色數據點。

fig, ax = plt.subplots()

for x, y, yerr, color in zip(nh_noUL_val.keys(), nh_noUL_val.values(), asymetric_error.values(),
                             noUL_colors.values()):

    ax.errorbar(x,y , yerr = asymetric_error,  color = color, marker = 'o', ms = 5)
plt.show()

但是,這給了我:

ValueError: err must be [ scalar | N, Nx1 or 2xN array-like ]

誠然,我對 python 有點陌生,並不完全理解數組。 但我的猜測是我的asymmetric_error.values()實際上是一個 Nx2 數組? 如果是這種情況,我如何將其變成 2xN 形式? 如果不是這樣,我的代碼有什么問題?

您正在為yerr參數傳遞字典。 它需要一個scalar or array-like, shape(N,) or shape(2,N),

 ax.errorbar(x,y , yerr = asymetric_error,...

你想要不對稱的條形,所以yerr需要是 shape(2,N) 這意味着兩個項目,每個項目都有 N 個值。 由於您在迭代時一次繪制一個點,因此 N=1。 yerr需要是[[neg_error][pos_error]]

您的 for 語句需要像這樣分別捕獲這兩個錯誤。

for x, y, (neg_err,pos_err), color in zip(nh_noUL_val.keys(), nh_noUL_val.values(),
                                          asymetric_error.values(), noUL_colors.values()):
    #print(x, y, yerr, color)
    ax.errorbar(x,y , yerr=[[neg_err],[pos_err]],  color=color,marker='o', ms=5)

一個警告。 您的循環依賴於三個字典的順序相同。 如果您使用的是 Python 3.7+,如果它們以相同的順序構造,那也不是問題。 如果您使用的是 3.5-,則需要確保每個字典中的值都用於相同的鍵。 像這樣的東西:

for x,y in nh_noUL_val.items():
    color = noUL_colors[x]
    neg, pos = asymetric_error[x]
    ax.errorbar(x,y,yerr=[[neg],[pos]],color=colors,marker='o', ms=5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM