How to add error bars in matplotlib for multiple groups from dataframe?

Viewed 3445

I've run multiple regressions and stored the coefficients and standard errors into a data frame like this:

Data frame

I wanted to make a graph that shows how the coefficient changes for each group over time, like so:

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

Which produces: enter image description here

But I would like to include error bars using the 'stderr' data from my main data set. I think I can do it using 'plt.errorbar'. But can't seem to figure out how to make it work. At the moment, I've tried adding the 'plt.errorbar line and experimenting different with different iterations:

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

As you can see, it seems to be creating it's own group/line in the graph. I think I would know how to use 'plt.errorbar' if I had just one group, but I don't have a clue how to make it work for 3 groups. Is there some way of making 3 versions of 'plt.errorbar' so I can create the error bars for each group separately? Or is there something simpler?

1 Answers

You need to iterate through the different groups, and plot the errorbar separately, what you have above is plotting all the error bars at one go:

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

Related