上限且有上限错误

时间:2018-08-29 08:22:11

标签: python matplotlib errorbar

是否有一个上限(带有向下箭头),且该点的中心位于最佳值,同时又有上限误差?

类似这样的东西:

enter image description here

我正在尝试:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([10, 15, 20, 25, 30, 35])
x_el = np.array([1, 1, 2, 25, 1, 2, 1])
x_eu = np.array([1, 1, 2, 1, 1, 2, 1])
y = np.array([29, 15, 9, 10, 25, 14])
y_el = np.array([1, 1, 2, 1, 1, 2, 1])
y_eu = np.array([11,1,2,1,1,2,1])

fig, ax = plt.subplots()

for i in range(len(x)):
    if (x[i] - x_el[i]) == 0:
        el = 0
        ax.errorbar(x[i], y[i], yerr=[[y_el[i]], [y_eu[i]]], xerr=[[el],[x_eu[i]]],
                    c='b', capsize=2, elinewidth=1, marker='o',
                    xuplims=True)
    else:
        ax.errorbar(x[i], y[i], yerr=[[y_el[i]], [y_eu[i]]], xerr=[[x_el[i]], [x_eu[i]]],
                    c='b', capsize=2, elinewidth=1, marker='o')

但这是结果:

enter image description here

点编号4既没有上限误差,也没有上限误差。

1 个答案:

答案 0 :(得分:1)

简短的回答是,但是您必须分别绘制上限和误差线。让我们从正确绘制正常误差线开始。如果您的数据已经在numpy数组中,则无需循环即可完成此操作:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([10, 15, 20, 25, 30, 35])
x_el = np.array([1, 1, 2, 25, 1, 2])
x_eu = np.array([1, 1, 2, 1, 1, 2])
y = np.array([29, 15, 9, 10, 25, 14])
y_el = np.array([1, 1, 2, 1, 1, 2])
y_eu = np.array([11, 1, 2, 1, 1, 2])

fig, ax = plt.subplots()

mask = (x != x_el)

ax.errorbar(x, y, yerr=[y_el, y_eu], xerr=[x_el * mask, x_eu],
            c='b', capsize=2, elinewidth=1, marker='o', linestyle='none')

请注意,我将误差线数组的大小减小到与x相同,这使我可以使用!=运算符来计算掩码。由于您对除x_el中的误差线之外的所有误差线都感兴趣,因此我乘以掩码。 mask是一个布尔值,任何被掩盖的错误栏都将以这种方式设置为零。此时,其他所有条形图均已正确绘制:

enter image description here

现在您可以使用相同的蒙版(但倒置)来绘制上限:

ax.errorbar(x[~mask], y[~mask], xerr=x_el[~mask],
            c='b', capsize=2, elinewidth=1, marker='o', linestyle='none',
            xuplims=True)

结果是

enter image description here

如果您对伸长到零的长箭头不感兴趣,可以将其缩短为任意大小:

ax.errorbar(x[~mask], y[~mask], xerr=1,
            c='b', capsize=2, elinewidth=1, marker='o', linestyle='none',
            xuplims=True)

enter image description here

替代

由于xuplims接受布尔值数组,因此您甚至可以通过一个绘图调用就非常接近。但是,在任何地方为True都将消除右栏:

mask = (x == x_el)
ax.errorbar(x, y, yerr=[y_el, y_eu], xerr=[x_el, x_eu],
            c='b', capsize=2, elinewidth=1, marker='o', linestyle='none',
            xuplims=mask)

enter image description here

在这种情况下,您最终必须填写右栏:

ax.errorbar(x[mask], y[mask], xerr=[np.zeros_like(x_eu)[mask], x_eu[mask]],
            c='b', capsize=2, elinewidth=1, marker='o', linestyle='none')

enter image description here

相关问题