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

Python Pandas - สร้าง Horizontal Bar Chart

บทนำ

ใช้ pandas.DataFrame.plot.barh วาด Horizontal Bar Chart เปรียบเทียบหมวดหมู่ที่เป็นแบบไม่ต่อเนื่อง

ขั้นตอน

  1. นำเข้า pandas และ matplotlib
  2. สร้าง DataFrame ข้อมูลรถยนต์ (Car, Cubic_Capacity, Reg_Price, Units_Sold)
  3. วาด Horizontal Bar Chart:
    dataFrame.plot.barh(x='Car', y='Cubic_Capacity', 
        title='Car Specifications', color='blue')
  4. ตั้งชื่อแกนและแสดงผล

โค้ดเต็ม

import pandas as pd
import matplotlib.pyplot as plt

dataFrame = pd.DataFrame({
    "Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],
    "Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
    "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
    "Units_Sold": [100, 110, 150, 80, 200, 90]
})

dataFrame.plot.barh(x='Car', y='Cubic_Capacity', 
    title='Car Specifications', color='blue')
plt.xlabel("CC (Cubic Capacity)")
plt.show()

ผลลัพธ์

ได้ Horizontal Bar Chart แสดง Cubic Capacity ของรถแต่ละคัน