Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การแสดง Scatter Plot ด้วย Seaborn ใน Python

Scatter Plot แสดงความสัมพันธ์ระหว่าง 2 ตัวแปรตัวเลข (Numerical Variables) แต่ละจุด = 1 Observation

Seaborn มี jointplot() (Scatter + Marginal Distributions), scatterplot() (Basic), relplot() (FacetGrid)

ตัวอย่างโค้ด (jointplot)


import seaborn as sb
from matplotlib import pyplot as plt

df = sb.load_dataset('iris')
sb.jointplot(x='petal_length', y='petal_width', data=df)
plt.show()

ผลลัพธ์

การแสดง Scatter Plot ด้วย Seaborn ใน Python

คำอธิบาย

  • โหลดข้อมูล Iris

  • jointplot(x, y, data) - Scatter Plot พร้อม Marginal Histograms/KDE ด้านข้าง

  • แสดงความสัมพันธ์ Petal Length vs Petal Width

ฟังก์ชัน Scatter Plot ใน Seaborn

Functionคำอธิบายเหมาะสำหรับ
scatterplot()Basic Scatter PlotSimple, Customizable
jointplot()Scatter + Marginal DistributionsDistribution + Relationship
relplot()FacetGrid Scatter/LineSubplots by Category (col/row/hue)
lmplot()Scatter + Regression LineLinear Relationship
pairplot()Pairwise Scatter MatrixMulti-variable Overview

ตัวอย่าง scatterplot() - ควบคุมรายละเอียดมากกว่า


import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

# Basic scatterplot with hue, style, size
sns.scatterplot(
    data=df,
    x='petal_length',
    y='petal_width',
    hue='species',      # สีตาม Species
    style='species',    # Marker ตาม Species
    size='sepal_length',# ขนาดจุดตาม Sepal Length
    sizes=(20, 200),    # Range ของ Size
    alpha=0.7,
    palette='Set1'
)
plt.title("Iris: Petal Length vs Width")
plt.show()

ตัวอย่าง pairplot() - ดูทุก Pair พร้อมกัน


# Pairwise Scatter Matrix
sns.pairplot(df, hue='species', diag_kind='kde')
plt.show()

การปรับแต่ง Scatter Plot


# Regression Line
sns.lmplot(data=df, x='petal_length', y='petal_width', hue='species')

# Custom Markers
markers = {'setosa': 'o', 'versicolor': 's', 'virginica': 'D'}
sns.scatterplot(data=df, x='petal_length', y='petal_width', 
                hue='species', style='species', markers=markers)

# Marginal KDE แทน Histogram
sns.jointplot(data=df, x='petal_length', y='petal_width', kind='kde')

Interpretation: Iris Dataset แสดง Petal Length/Width แยก Species ได้ชัด (Setosa แยกจาก Versicolor/Virginica)