วิธีสร้างแผนการกระจายของทะเลโดยมีค่าสัมประสิทธิ์สหสัมพันธ์
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อสร้าง Scatterplot ใน Seaborn และเพิ่ม ค่าสัมประสิทธิ์สหสัมพันธ์ ให้กับพล็อต:
import scipy import matplotlib. pyplot as plt import seaborn as sns #calculate correlation coefficient between x and y r = scipy. stats . pearsonr (x=df. x , y=df. y )[0] #create scatterplot sns. scatterplot (data=df, x=df. x , y=df. y ) #add correlation coefficient to plot plt. text (5, 30, ' r = ' + str ( round (r,2)))
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: สร้างแผนการกระจายของทะเลโดยมีค่าสัมประสิทธิ์สหสัมพันธ์
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งแสดงคะแนนและการช่วยเหลือของผู้เล่นบาสเก็ตบอลหลายคน:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'C', 'C', 'C', 'D', 'D'], ' points ': [12, 11, 18, 15, 14, 20, 25, 24, 32, 30], ' assists ': [4, 7, 7, 8, 9, 10, 10, 12, 10, 15]}) #view DataFrame print (df) team points assists 0 to 12 4 1 to 11 7 2 To 18 7 3 to 15 8 4 B 14 9 5 C 20 10 6 C 25 10 7 C 24 12 8 D 32 10 9 D 30 15
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้างแผนภาพกระจายเพื่อแสดงความสัมพันธ์ระหว่างการส่งผ่านและจุด และยังใช้ฟังก์ชัน pearsonr() ของ scipy เพื่อคำนวณค่าสัมประสิทธิ์สหสัมพันธ์ระหว่างตัวแปรทั้งสองนี้:
import scipy import matplotlib. pyplot as plt import seaborn as sns #calculate correlation coefficient between assists and points r = scipy. stats . pearsonr (x=df. assists , y=df. points )[0] #create scatterplot sns. scatterplot (data=df, x=df. assists , y=df. points ) #add correlation coefficient to plot plt. text (5, 30, ' r = ' + str ( round (r,2)))

จากผลลัพธ์เราจะเห็นว่าค่าสัมประสิทธิ์สหสัมพันธ์ของเพียร์สันระหว่างแอสซิสต์และแต้มคือ 0.78
ที่เกี่ยวข้อง: อะไรคือความสัมพันธ์ที่ “แข็งแกร่ง”?
โปรดทราบว่าเราใช้ฟังก์ชัน round() เพื่อปัดเศษค่าสัมประสิทธิ์สหสัมพันธ์ให้เป็นทศนิยมสองตำแหน่ง
คุณสามารถปัดเศษทศนิยมตามจำนวนตำแหน่งต่างๆ ได้ตามใจชอบ และใช้อาร์กิวเมนต์ ขนาดตัวอักษร เพื่อเปลี่ยนขนาดตัวอักษรของค่าสัมประสิทธิ์สหสัมพันธ์บนโครงเรื่องได้ตามใจชอบ:
import scipy import matplotlib. pyplot as plt import seaborn as sns #calculate correlation coefficient between assists and points r = scipy. stats . pearsonr (x=df. assists , y=df. points )[0] #create scatterplot sns. scatterplot (data=df, x=df. assists , y=df. points ) #add correlation coefficient to plot plt. text (5, 30, ' r= '+ str ( round (r,4)), fontsize= 20 ))

โปรดทราบว่าขณะนี้ค่าสัมประสิทธิ์สหสัมพันธ์ถูกปัดเศษเป็นทศนิยมสี่ตำแหน่ง และขนาดตัวอักษรมีขนาดใหญ่กว่าในตัวอย่างก่อนหน้านี้มาก
หมายเหตุ : คุณสามารถค้นหาเอกสารฉบับเต็มสำหรับฟังก์ชัน seaborn scatterplot() ได้ที่นี่
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำหน้าที่ทั่วไปอื่นๆ ในทะเล:
วิธีการพล็อตการกระจายใน Seaborn
วิธีเรียงลำดับ boxplot บนแกน x ใน Seaborn
วิธีเพิ่มตารางลงในพล็อต Seaborn