matplotlib在带索引的for循环中绘制非对称错误栏

问题描述 投票:0回答:1

我正在尝试使用带有不对称错误栏的plt.errorbar来绘制一些带有for循环的数组。我知道在这个例子中使用没有索引的数组会更容易,但我想在其他代码中使用plt.errorbar中的索引,并在索引i上使用某些条件。

这是示例代码:

   import numpy as np
   import matplotlib.pyplot as plt


    x=[ 0.007206,  0.043695,  0.372777,  0.464819,  0.337386,  0.249215,  0.395453,
      0.222331,  0.11715,   0.101464,  0.645596,  0.228634,  0.187252,  0.283026,
      0.596368,  0.019066,  0.300215,  0.174883,  0.331613,  0.175409,  0.858567, 0.895389]

    y=[  0.327811,  33.3177,     1.36996,   41.9717,     1.18497,    1.05182,    2.28229,
       0.424775,   1.11758,    4.5135,     2.70709,    1.26611,   10.8293,     4.92649,
      31.4483,     0.403496,   1.14471,    1.72301,   12.081,      0.501048,  13.6858,
       4.58709 ]

    xel=[ 0.034065,  0.096869,  0.046961,  0.13575,   0.086615,  0.070706,  0.068376,
      0.132277,  0.12079,   0.102303,  0.048192,  0.070823,  0.067665,  0.07266,
      0.093411,  0.040662,  0.089356,  0.098089,  0.137559,  0.146229,  0.038649,
      0.030372]
    xeu=[ 0.032612,  0.092047,  0.04424,   0.151329,  0.077828,  0.066373,  0.065701,
      0.123756,  0.09371,   0.086466,  0.047322,  0.069837,  0.070206,  0.058787,
      0.088777,  0.045837,  0.098174,  0.105,     0.148259,  0.14845,   0.133334,
      0.104611]

    for i in range(21):
        plt.errorbar(x[i], y[i], xerr=[xel[i],xeu[i]], fmt='.')

    plt.show()

输出错误是:

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

此外,如果我尝试对称错误栏(plt.errorbar(x[i], y[i], xerr=xallel[i]))它的工作原理。所以我不明白问题出在哪里。

我需要索引,因为我需要在循环顶部的索引i上添加一个条件。例如:

for i in range(21):
    if y[i]<1.0:
        plt.errorbar(x[i], y[i], xerr=[xel[i], xeu[i]], fmt='.', color='red')
    else:
        plt.errorbar(x[i], y[i], xerr=[xel[i], xeu[i]], fmt='.', color='b')

我该如何解决这个问题?我正在使用anaconda Python 3.6。

python loops numpy matplotlib errorbar
1个回答
1
投票

你的xerr数组不是2xN,它应该是2x1:

xerr=[[xel[i]],[xeu[i]]]

您可以避免循环,matplotlib通常支持一次绘制多个值。

plt.errorbar(x, y, xerr=[xel,xeu], fmt='.')
© www.soinside.com 2019 - 2024. All rights reserved.