亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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()

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

查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號