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

วิธีพลอต Bar Graph จาก Pandas Series ใน Matplotlib


ภาพรวม

สาธิตการสร้าง Bar Chart จาก Pandas DataFrame โดยใช้เมธอด plot(kind='bar')

ขั้นตอน

  1. สร้าง Dictionary ข้อมูล
  2. แปลงเป็น Pandas DataFrame
  3. เรียก df.plot(kind='bar')
  4. แสดงผลด้วย 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 Bar
  • df.plot(kind='barh') สำหรับ Horizontal Bar
  • ใช้ ax= เพื่อพลอตบน Subplot เฉพาะ