การจำกัดกลุ่มที่แสดงใน countplot
เพื่อจำกัดจำนวนกลุ่มใน Seaborn countplot สามารถใช้ตัวแปร group_count ในอาร์กิวเมนต์ของเมธอด countplot()
ขั้นตอน
- สร้าง figure และ subplots 2 ชุด
- สร้าง DataFrame ด้วย Pandas พร้อม 2 คีย์
- กำหนดตัวแปร group_count เพื่อจำกัดจำนวนกลุ่มใน countplot()
- ใช้เมธอด countplot() แสดงจำนวนการสังเกตในแต่ละกลุ่มหมวดหมู่ด้วยแท่ง
- ปรับ padding ระหว่างและรอบ subplots
ตัวอย่างโค้ด
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
f, axes = plt.subplots(1, 2)
df = pd.DataFrame(dict(col1=np.linspace(1, 10, 5),
col2=np.linspace(1, 10, 5),
col3=np.linspace(1, 10, 5)))
group_count = 1
sns.countplot(df.col1, x='col1', color="red", ax=axes[0],
order=df.col1.value_counts().iloc[:group_count].index)
sns.countplot(df.col2, x="col2", color="green", ax=axes[1],
order=df.col2.value_counts().iloc[:group_count].index)
plt.tight_layout()
plt.show()
ผลลัพธ์
