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

วิธีจำกัดจำนวนกลุ่มใน Seaborn countplot ด้วย Matplotlib


การจำกัดกลุ่มที่แสดงใน countplot

เพื่อจำกัดจำนวนกลุ่มใน Seaborn countplot สามารถใช้ตัวแปร group_count ในอาร์กิวเมนต์ของเมธอด countplot()

ขั้นตอน

  1. สร้าง figure และ subplots 2 ชุด
  2. สร้าง DataFrame ด้วย Pandas พร้อม 2 คีย์
  3. กำหนดตัวแปร group_count เพื่อจำกัดจำนวนกลุ่มใน countplot()
  4. ใช้เมธอด countplot() แสดงจำนวนการสังเกตในแต่ละกลุ่มหมวดหมู่ด้วยแท่ง
  5. ปรับ 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()

ผลลัพธ์

วิธีจำกัดจำนวนกลุ่มใน Seaborn countplot ด้วย Matplotlib