为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕虎7371278 2022-12-20 14:00:20
我运行了多重回归并将系数和标准误差存储到这样的数据框中:我想制作一个图表来显示每个组的系数随时间的变化情况,如下所示:import matplotlib.pyplot as pltimport seaborn as snsplt.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.showplt.savefig('eventstudygraph.png')哪个产生:但我想使用我的主数据集中的“stderr”数据来包含错误栏。我想我可以使用“plt.errorbar”来做到这一点。但似乎无法弄清楚如何让它发挥作用。目前,我尝试添加 'plt.errorbar 行并尝试不同的迭代:import matplotlib.pyplot as pltimport seaborn as snsplt.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.showplt.savefig('eventstudygraph.png')如您所见,它似乎在图表中创建了自己的组/线。如果我只有一组,我想我会知道如何使用“plt.errorbar”,但我不知道如何让它适用于 3 个组。有什么方法可以制作 3 个版本的“plt.errorbar”,这样我就可以分别为每个组创建错误栏了吗?或者有更简单的东西吗?
查看完整描述

1 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

您需要遍历不同的组,并分别绘制误差线,上面的内容是一次绘制所有误差线:


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

//img1.sycdn.imooc.com//63a1503f00011a4708260466.jpg

查看完整回答
反对 回复 2022-12-20
  • 1 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号