简体   繁体   中英

How to add error bars for displot in seaborn

The following are my codes. I would like to generate a plot of the exponential distribution with error bars as the square root of the count in each bin. But it seems that there's no error bar for displot . I wonder what I could do. Thank you very much.

x = np.random.exponential(2.2 * 10**(-6), 10000)
p = sns.displot(x)

No error is shown, as the histogram shows the exact counts of the given sample. To get error bars, multiple sets of samples need to be counted.

Some notes about the following example:

  • the example code makes 10 samples of the distribution and calculates the histogram for each
  • the results are stored in a dataframe (the dataframe also stores a label that indicates to which sample the count belongs, but this label is not used in the current visualisation)
  • a bar plot shows the count for each bin, with error bars as the same bin appears 10 times in the dataframe
  • seaborn's bar plots use categorical x-axis (internally placed at positions 0,1,2,...); the bin borders can be shown at the halves
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

N = 10000
K = 10

lbl = np.repeat(np.arange(K), N)
bins = np.linspace(0, 1e-5, 21)
counts = np.zeros(shape=(K, len(bins) - 1))
for i in range(K):
    x = np.random.exponential(2.2 * 10 ** (-6), N)
    counts[i], _ = np.histogram(x, bins)
df = pd.DataFrame({'count': counts.ravel(),
                   'bin': np.tile(bins[:-1], K),
                   'label': np.repeat(np.arange(K), len(bins) - 1)})
g = sns.catplot(data=df, x='bin', y='count', kind='bar', height=4, aspect=3)
g.ax.set_xticks(np.arange(-0.5, len(bins) - 1))
g.ax.set_xticklabels([f'{b / 10e-5:.1f}e-5' for b in bins])
g.set(xlabel='')
plt.tight_layout()
plt.show()

指数分布直方图的 sns.catplot

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