ใส่คำอธิบายประกอบบน Seaborn Jointplot

การสร้างกราฟชุดข้อมูล "เคล็ดลับ" เป็นแผนร่วม ฉันต้องการติดป้ายกำกับค่าผิดปกติ 10 อันดับแรก (หรือค่าผิดปกติอันดับสูงสุด) บนกราฟตามดัชนีจากดาต้าเฟรม "เคล็ดลับ" ฉันคำนวณค่าคงเหลือ (ระยะห่างจากเส้นเฉลี่ย) เพื่อค้นหาค่าผิดปกติ โปรดละเว้นข้อดีของวิธีการตรวจจับค่าผิดปกตินี้ ฉันแค่อยากจะอธิบายกราฟตามสเป็ค

import seaborn as sns
sns.set(style="darkgrid", color_codes=True)

tips = sns.load_dataset("tips")
model = pd.ols(y=tips.tip, x=tips.total_bill)
tips['resid'] = model.resid

#indices to annotate
tips.sort_values(by=['resid'], ascending=[False]).head(5)

ป้อนคำอธิบายรูปภาพที่นี่

tips.sort_values(by=['resid'], ascending=[False]).tail(5)

ป้อนคำอธิบายรูปภาพที่นี่

%matplotlib inline
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
                  xlim=(0, 60), ylim=(0, 12), color="r", size=7)

ฉันจะใส่คำอธิบายประกอบค่าผิดปกติ 10 อันดับแรก (ค่าตกค้างที่ใหญ่ที่สุด 5 และค่าน้อยที่สุด 5 ค่า) บนกราฟด้วยค่าดัชนีของแต่ละจุด (ค่าตกค้างที่ใหญ่ที่สุด) เพื่อให้มีสิ่งนี้:

ป้อนคำอธิบายรูปภาพที่นี่


person Thomas Matthew    schedule 24.03.2017    source แหล่งที่มา


คำตอบ (1)


คุณสามารถใช้ matplotlib annotate เพื่อสร้างคำอธิบายประกอบไปยังจุดหนึ่งได้ แนวคิดคือการวนซ้ำบนดาต้าเฟรมและวางคำอธิบายประกอบในตำแหน่งที่เกี่ยวข้องที่กำหนดโดยคอลัมน์ "tip" และ "total_bill"

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="darkgrid", color_codes=True)

tips = sns.load_dataset("tips")
model = pd.ols(y=tips.tip, x=tips.total_bill)
tips['resid'] = model.resid

g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
                  xlim=(0, 60), ylim=(0, 12), color="r", size=7)

#indices to annotate
head = tips.sort_values(by=['resid'], ascending=[False]).head(5)

tail = tips.sort_values(by=['resid'], ascending=[False]).tail(5)

def ann(row):
    ind = row[0]
    r = row[1]
    plt.gca().annotate(ind, xy=(r["total_bill"], r["tip"]), 
            xytext=(2,2) , textcoords ="offset points", )

for row in head.iterrows():
    ann(row)
for row in tail.iterrows():
    ann(row)

plt.show()

ป้อนคำอธิบายรูปภาพที่นี่


โปรดทราบว่า ณ เวอร์ชัน 0.20 ของ pandas นั้น pandas.ols ถูกลบออกแล้ว หากต้องการแทนที่ อาจใช้ โมเดล OLS จาก statsmodels บรรทัดที่เกี่ยวข้องจะอ่านว่า:

import statsmodels.api as sm
model = sm.OLS(tips.tip, tips.total_bill)
tips['resid'] = model.fit().resid

โปรดทราบว่าผลลัพธ์จะแตกต่างออกไปเล็กน้อย (อาจเนื่องมาจากการถ่วงน้ำหนักที่แตกต่างกัน)

person ImportanceOfBeingErnest    schedule 24.03.2017
comment
การเรียงลำดับและการตัดทอน iterables head และ tail เป็นวิธีที่ดีในการลดจำนวนการวนซ้ำ โดยเฉพาะสำหรับ dataframe ขนาดใหญ่เช่นชุดข้อมูลจริงของฉัน ขอบคุณ - person Thomas Matthew; 25.03.2017
comment
ฉันอัปเดตคำตอบด้วยวิธีแก้ปัญหาสำหรับแพนด้าเวอร์ชันใหม่กว่า - person ImportanceOfBeingErnest; 02.07.2017