พารามิเตอร์ order ใน sns.violinplot() ควบคุมลำดับการแสดงหมวดหมู่บนแกน categorical (x หรือ y) เหมือนกับ boxplot และ swarmplot ทำให้การนำเสนอข้อมูลเป็นไปตามเจตนา
ขั้นตอนการทำงาน
1. นำเข้าไลบรารี
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
2. โหลดข้อมูล Cricketers.csv
dataFrame = pd.read_csv(r"C:\Users\amit_\Desktop\Cricketers.csv")
3. วาด Violin Plot ระบุ order ของ Role
sns.violinplot(
x='Role',
y='Age',
order=["Batsman", "Bowler"],
data=dataFrame
)
โค้ดตัวอย่างสมบูรณ์
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
dataFrame = pd.read_csv(r"C:\Users\amit_\Desktop\Cricketers.csv")
# Violin plot ควบคุมลำดับ Role
sns.violinplot(
x='Role',
y='Age',
order=["Batsman", "Bowler"],
data=dataFrame
)
plt.show()
ผลลัพธ์
Violin plot แสดงการกระจายอายุ (Age) ของ Batsman (ซ้าย) และ Bowler (ขวา) ตามลำดับที่ระบุ

การใช้งาน order และ hue_order
# order: ควบคุมลำดับหมวดหมู่หลัก (x หรือ y)
sns.violinplot(x='Role', y='Age', order=["Batsman", "Bowler"], data=df)
# hue_order: ควบคุมลำดับหมวดหมู่ hue (legend)
sns.violinplot(x='Role', y='Age', hue='Academy', hue_order=["A", "B", "C"], data=df)
# split=True: แยก violin ครึ่งซ้าย-ขวา ต่อ hue (ต้องมี hue)
sns.violinplot(x='Role', y='Age', hue='Academy', split=True, data=df)
ตัวอย่าง: เรียงตาม Median Age
# คำนวณ median age ต่อ Role
role_order = dataFrame.groupby('Role')['Age'].median().sort_values().index
# ใช้ order นั้น
sns.violinplot(x='Role', y='Age', order=role_order, data=dataFrame)
พารามิเตอร์ Violin Plot ที่น่าสนใจ
| พารามิเตอร์ | คำอธิบาย |
|---|---|
inner | "box", "quartile", "point", "stick", None |
split | True/False แยก violin ครึ่งซ้ายขวาต่อ hue |
scale | "area" (default), "count", "width" |
scale_hue | True/False scale แยกต่อ hue |
bw | Bandwidth ของ KDE |
cut | ตัดหัวหาง violin (default=2) |
Violin Plot แบบแนวนอน
# สลับ x, y
sns.violinplot(x='Age', y='Role', order=["Batsman", "Bowler"], data=dataFrame)