gpt4 book ai didi

python - 如何在 matplotlib 中为数据帧中的多个组添加误差线?

转载 作者:行者123 更新时间:2023-12-02 02:49:52 24 4
gpt4 key购买 nike

我运行了多重回归并将系数和标准误差存储到如下数据框中:

Data frame

我想制作一个图表来显示每个组的系数如何随时间变化,如下所示:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(14,8))

sns.set(style= "whitegrid")

sns.lineplot(x="time", y="coef",
hue="group",
data=eventstudy)
plt.axhline(y=0 , color='r', linestyle='--')
plt.legend(bbox_to_anchor=(1, 1), loc=2)
plt.show
plt.savefig('eventstudygraph.png')

它产生: enter image description here

但我想使用主数据集中的“stderr”数据包含错误栏。我想我可以使用“plt.errorbar”来做到这一点。但似乎无法弄清楚如何使其发挥作用。目前,我尝试添加 'plt.errorbar 行并尝试不同的迭代:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(14,8))

sns.set(style= "whitegrid")

sns.lineplot(x="time", y="coef",
hue="group",
data=eventstudy)
plt.axhline(y=0 , color='r', linestyle='--')
plt.errorbar("time", "coef", xerr="stderr", data=eventstudy)
plt.legend(bbox_to_anchor=(1, 1), loc=2)
plt.show
plt.savefig('eventstudygraph.png')

enter image description here

正如您所看到的,它似乎正在图表中创建自己的组/线。我想如果我只有一组,我会知道如何使用“plt.errorbar”,但我不知道如何让它适用于 3 个组。有没有某种方法可以制作 3 个版本的“plt.errorbar”,以便我可以分别为每个组创建误差线?或者有更简单的吗?

最佳答案

您需要迭代不同的组,并分别绘制误差条,上面的内容是一次性绘制所有误差条:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(111)
df = pd.DataFrame({"time":[1,2,3,4,5]*3,"coef":np.random.uniform(-0.5,0.5,15),
"stderr":np.random.uniform(0.05,0.1,15),
"group":np.repeat(['Monthly','3 Monthly','6 Monthly'],5)})

fig,ax = plt.subplots(figsize=(14,8))
sns.set(style= "whitegrid")
lvls = df.group.unique()
for i in lvls:
ax.errorbar(x = df[df['group']==i]["time"],
y=df[df['group']==i]["coef"],
yerr=df[df['group']==i]["stderr"],label=i)
ax.axhline(y=0 , color='r', linestyle='--')
ax.legend()

enter image description here

关于python - 如何在 matplotlib 中为数据帧中的多个组添加误差线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62177520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com