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

Python Pandas - พล็อต Grouped Horizontal Bar Chart ทุกคอลัมน์

การสร้าง Grouped Horizontal Bar Chart** (กราฟแท่งแนวนอนกลุ่ม) สำหรับทุกคอลัมน์ตัวเลขใน DataFrame สามารถทำได้ง่ายด้วยเมธอด plot.barh() โดยไม่ต้องระบุ x, y แยกต่างหาก Pandas จะใช้ index เป็นแกน Y และคอลัมน์ตัวเลขทั้งหมดเป็นกลุ่มแท่ง

ขั้นตอนการทำงาน

1. นำเข้าไลบรารี

import pandas as pd
import matplotlib.pyplot as plt

2. สร้าง DataFrame หลายคอลัมน์ตัวเลข

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],
})

3. พล็อต Grouped Horizontal Bar Chart

dataFrame.plot.barh(title='Car Specifications', color=("blue", "orange"))

โค้ดตัวอย่างสมบูรณ์

import pandas as pd
import matplotlib.pyplot as plt

# สร้าง DataFrame
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],
})

# พล็อต Grouped Horizontal Bar Chart
dataFrame.plot.barh(title='Car Specifications', color=("blue", "orange"))

# แสดงกราฟ
plt.show()

ผลลัพธ์

กราฟแท่งแนวนอน กลุ่มตาม Car (แกน Y) มีแท่ง 2 สีต่อคัน: สีน้ำเงิน = Cubic_Capacity, สีส้ม = Reg_Price

Python Pandas - พล็อต Grouped Horizontal Bar Chart ทุกคอลัมน์

คำอธิบาย

  • plot.barh() = horizontal bar chart (แท่งนอน)
  • Pandas จะใช้ index เป็นแกน Y อัตโนมัติ (ในที่นี้คือ 0-5)
  • คอลัมน์ตัวเลขทั้งหมด (Cubic_Capacity, Reg_Price) จะกลายเป็นกลุ่มแท่ง
  • คอลัมน์ Car (object/string) จะถูกละเว้น ไม่ได้พล็อต

ปรับแต่งเพิ่มเติม

# ตั้ง index ให้เป็น Car เพื่อแสดงชื่อรถบนแกน Y
dataFrame.set_index('Car').plot.barh(title='Car Specifications', color=("blue", "orange"))

# เพิ่ม legend, label
ax = dataFrame.set_index('Car').plot.barh(title='Car Specifications', color=("blue", "orange"))
ax.set_xlabel("Value")
ax.set_ylabel("Car Model")
plt.legend(title="Specification")
plt.tight_layout()
plt.show()

ประเภท Plot อื่นๆ ของ DataFrame.plot

  • .plot.bar() - Vertical bar chart (แท่งตั้ง)
  • .plot.barh() - Horizontal bar chart (แท่งนอน)
  • .plot.line() - Line chart
  • .plot.scatter() - Scatter plot
  • .plot.box() - Box plot
  • .plot.hist() - Histogram
  • .plot.area() - Area chart