Python 如何为dataframe中的多个组在matplotlib中添加错误条?

Python 如何为dataframe中的多个组在matplotlib中添加错误条?,python,matplotlib,graph,seaborn,Python,Matplotlib,Graph,Seaborn,我已经运行了多元回归,并将系数和标准误差存储到如下数据框中: 我想制作一张图表,显示每组的系数随时间的变化,如下所示: 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=

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

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

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')
产生:

但是我想使用主数据集中的“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')


如您所见,它似乎在图中创建自己的组/线。如果我只有一个小组,我想我会知道如何使用'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()

又一次,愚蠢的狼,你来救我了,我非常感激。我甚至没有意识到可以将for循环添加到matplotlib配置中,因此我相信这在将来会很方便。线条的颜色与图例上显示的颜色不同。它在您提供的解决方案中也做了同样的事情。我相信我可以调查找出这个问题,但我只是想为其他人做标记。(如果我解决了会更新)@Jameson,谢谢你指出!你说得对,它又重新策划了。如果x值是连续的,则plt.errorbar函数将连接这些行。。所以,是的,你不需要sns.lineplot来开始…太棒了。谢谢我确实怀疑这是事实,但不知道如何在不牺牲传说本身的情况下纠正它。