簡體   English   中英

MatPlotLib 中的不對稱誤差線

[英]Asymmetric Error Bars in MatPlotLib

我有一個日志日志 plot 並希望 plot 6 個數據點之一的正誤差條。 rest 可以有正負。 我該如何解決?

通常這是我繪制誤差線的方式:

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')

閱讀plt.errorbar的文檔,如果要繪制非對稱錯誤欄,則必須使用xerr的參數作為形狀2xN的序列。 如果這樣做,則相對於數據在-row1和+ row2處繪制錯誤欄。 如果要僅為一個點繪制正誤差條,則應將下限定義為零。 我的意思是,如果您的數據是:

[x1, x2, ... , xn]

你必須給出序列:

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

作為xerr的論據。 希望能幫助到你。

下面是一個示例,說明如何在 matplotlib 中使用 plot 不對稱誤差線。 即使使用對數刻度,您也可以使用它。

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