ภาพรวม
สาธิตการสร้าง Bar Chart จาก Pandas DataFrame โดยใช้เมธอด plot(kind='bar')
ขั้นตอน
- สร้าง Dictionary ข้อมูล
- แปลงเป็น Pandas DataFrame
- เรียก
df.plot(kind='bar') - แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {'y=1/x': [1 / i for i in range(1, 10)],
'y=x': [i for i in range(1, 10)],
'y=x^2': [i * i for i in range(1, 10)],
'y=x^3': [i * i * i for i in range(1, 10)]}
df = pd.DataFrame(d)
df.plot(kind='bar')
plt.show()
ผลลัพธ์
Bar Chart แสดง 4 Series พร้อมกัน แต่ละ Series มีสีต่างกัน พร้อม Legend อัตโนมัติ
การปรับแต่งเพิ่มเติม
df.plot(kind='bar', stacked=True)สำหรับ Stacked Bardf.plot(kind='barh')สำหรับ Horizontal Bar- ใช้
ax=เพื่อพลอตบน Subplot เฉพาะ