简体   繁体   中英

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. The rest can have positive & negative. 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 . If you do so, errorbars are drawn at -row1 and +row2 relative to the data. 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 . Hope it helps.

Below is an example of how you can plot asymmetric error bars in matplotlib. 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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