简体   繁体   English

MatPlotLib 中的不对称误差线

[英]Asymmetric Error Bars in MatPlotLib

I have a loglog plot and would like to plot positive error bar for one of the 6 data points.我有一个日志日志 plot 并希望 plot 6 个数据点之一的正误差条。 The rest can have positive & negative. rest 可以有正负。 How do I work this out?我该如何解决?

Generally this is how I have plotted error bars:通常这是我绘制误差线的方式:

plt.loglog(vsini_rand, vsini_rand_lit, 'bo', label='Randich+1996')
plt.errorbar(vsini_rand, vsini_rand_lit, xerr = sig_rand, color = 'gray', fmt='.', zorder=1)
plt.loglog(x,y,'r-', zorder=3, label='1:1')

Reading the documentation of plt.errorbar , if you want to plot asymmetric errorbars, you would have to use the argument of xerr as a sequence of shape 2xN . 阅读plt.errorbar的文档,如果要绘制非对称错误栏,则必须使用xerr的参数作为形状2xN的序列。 If you do so, errorbars are drawn at -row1 and +row2 relative to the data. 如果这样做,则相对于数据在-row1和+ row2处绘制错误栏。 If you want to plot a positive error bar for only one point, you should define to zero the lower limit. 如果要仅为一个点绘制正误差条,则应将下限定义为零。 I mean, if your data is: 我的意思是,如果您的数据是:

[x1, x2, ... , xn]

you have to give the sequence: 你必须给出序列:

[x0-,x0+,x1-,x1+, ... , xn-,xn+] 

as the argument of xerr . 作为xerr的论据。 Hope it helps. 希望能帮助到你。

Below is an example of how you can plot asymmetric error bars in matplotlib.下面是一个示例,说明如何在 matplotlib 中使用 plot 不对称误差线。 You can use this even with a log-log scale.即使使用对数刻度,您也可以使用它。

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(10)

def generate_data(num_points, num_repetitions):
    n, reps = num_points, num_repetitions
    # Generate fake data
    x = np.linspace(0, 4*np.pi, n)
    ys = np.array([
        np.sin(x) + np.random.normal(0, scale=0.3, size=n) for _ in range(reps)
    ])

    yavg = np.mean(ys, axis=0)
    ymins = np.min(ys, axis=0)
    ymaxs = np.max(ys, axis=0)
    yerr = [
        np.abs(yavg-ymins), # lower error
        np.abs(yavg-ymaxs)  # upper error 
    ]
    return x, yavg, ymins, ymaxs, yerr

def format_ax(axes, x):
    for ax in axes:
        ax.set_xlim(min(x), max(x))
        ax.set_xticks([])
        ax.set_yticks([])

        
def make_plot():
    fig, axes = plt.subplots(1,2, figsize=(8, 3))

    x, yavg, ymins, ymaxs, yerr = generate_data(50, 3)
    axes[0].errorbar(x, yavg, yerr=yerr, c='tab:orange',  elinewidth=0.75, marker='.', linestyle='none')

    x, yavg, ymins, ymaxs, yerr = generate_data(100, 15)
    axes[1].plot(x, ymins, ls="--", c='tab:orange', alpha=0.4)
    axes[1].plot(x, ymaxs, ls="--", c='tab:orange', alpha=0.4)
    axes[1].errorbar(x, yavg, yerr=yerr, c='tab:orange', alpha=0.2, lw=0.75, linestyle='none')
    axes[1].plot(x, yavg, c='tab:orange')

    format_ax(axes, x)
    axes[0].set_title("Example 1")
    axes[1].set_title("Example 2")
    plt.show()

make_plot()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM