带置信区间的条形图在yerr参数下显得不同

问题描述 投票:0回答:1

首先,如果已经有人问过这个图的问题,很抱歉(我已经尾随看了好几个stackoverflow的帖子了)。

thedesiredplot

这个图有四个均值柱状图,上面的竖线代表的是误差范围(margin=mean+std*1.96)。

总之,我遇到的问题是,我的柱状图在没有yerr参数的情况下看起来很好。

myplotofmeans

然而,当我在plt.bar中引入yerr参数,yerr=df.std(axis=1)时,均值条就会变得以0为中心,而且很小。

myplotwithyerr

我真的不知道问题出在哪里,我也试过用置信区间做实验,但还是得到同样的图,当引入yerr参数时。

upper=[1.96*s[i] for i in range(4)], lower=[(-1.96)*s[i] for i in range(4)],
ci=list(zip(lower,upper))
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)], 
                  index=[1992,1993,1994,1995])

plt.figure(figsize=(8,8))
xt = [1992,1993,1994,1995]
plt.xticks(xt)
bar_plot = plt.bar(df.index, df.mean(axis=1),capsize=10)
#bar_plot = plt.bar(df.index, df.mean(axis=1),,yerr=df.std(axis=1)*1.96, capsize=10)
plt.show()
pandas dataframe matplotlib bar-chart confidence-interval
1个回答
0
投票

你可以用seaborn的barplot。

import seaborn as sns

sns.barplot(data=df.stack().reset_index(name='value'),
            x='level_0',
            y='value',
            color='C0')

输出。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.