python - 如何在 matplotlib 中为数据框中的多个组添加误差线?
问题描述
我已经运行了多次回归并将系数和标准误差存储到这样的数据框中:
我想制作一个图表,显示每个组的系数如何随时间变化,如下所示:
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()
推荐阅读
- java - 使用 Java 进行 Swift AES 加密
- java - 如何使用 java 项目修复 Selenium 的 Edge 和 chrome 驱动程序错误?
- c# - 如何使用模拟的 Uri 进行单元测试
- sql-server - 如果它们在日期范围sql之间,则求和值
- sql - SQL查询检查ID是否是另一个表的一部分
- reactjs - eslint错误时如何防止无法在CRA上编译
- ruby-on-rails - 延迟发送电子邮件
- angular - 动态形式的 FormArray
- aem - 关于资产取消发布 AEM OOTB 的电子邮件
- microsoft-graph-api - CompactToken 解析失败,错误代码为:80049217,而使用 Microsoft-graph-auth 0.2.0