ภาพรวม
การจัดเรียงแท่งใน Bar Chart ให้เรียงตามค่าจะทำให้อ่านข้อมูลง่ายขึ้น โดยใช้ sort_values() ของ DataFrame ก่อนพลอต
ขั้นตอนการทำงาน
- กำหนดขนาดฟิกเกอร์
- สร้าง DataFrame มีคอลัมน์ names และ marks
- สร้าง subplot แรก: พลอตข้อมูลต้นฉบับ
- สร้าง subplot ที่สอง: เรียงข้อมูลด้วย
df.sort_values('marks')แล้วพลอต - แสดงผลเพื่อเปรียบเทียบ
ตัวอย่างโค้ด
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(dict(
names=['John', 'James', 'David', 'Gary', 'Watson'],
marks=[23, 34, 30, 19, 20]
))
plt.subplot(121)
plt.bar('names', 'marks', data=df, color='red')
plt.title("Before Sorting")
plt.subplot(122)
df_sorted = df.sort_values('marks')
plt.bar('names', 'marks', data=df_sorted, color='orange')
plt.title("After Sorting (Ascending)")
plt.show()
ผลลัพธ์
ซ้าย: แท่งเรียงตามลำดับเดิม | ขวา: แท่งเรียงจากค่าน้อยไปมาก (Gary 19, Watson 20, John 23, David 30, James 34)

เคล็ดลับ
- ใช้
ascending=Falseเพื่อเรียงจากมากไปน้อย - สำหรับ horizontal bar chart ใช้
plt.barh()แทน - Seaborn มี
sns.barplot(order=...)ให้กำหนดลำดับได้โดยตรง