ในการวาดแท่งแนวนอนหลายแท่งในกราฟเดียวด้วย matplotlib สามารถทำตามขั้นตอนดังนี้:
ขั้นตอน
นำเข้าไลบรารี pandas, matplotlib, และ numpy
ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
สร้างอาร์เรย์สำหรับตำแหน่งแท่งแนวนอน
เริ่มต้นตัวแปร width สำหรับความกว้างแท่ง
สร้าง horizontal bar plot
ตั้งค่า Y-axis ticks และ tick labels พร้อมขีดจำกัด
วาง legend บน plot ตำแหน่ง upper right
แสดงรูปด้วยเมธอด show()
ตัวอย่าง
import pandas import matplotlib.pyplot as plt import numpy as np # ตั้งค่าขนาดรูป plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # อาร์เรย์ตำแหน่งแท่งแนวนอน ind = np.array([0, 1, 2]) # ความกว้างแท่ง width = 0.4 fig, ax = plt.subplots() # Horizontal bar plot ax.barh(ind, np.array([4, 3, 5]), width, color='orange', label='N') ax.barh(ind + width, np.array([2, 5, 2]), width, color='blue', label='M') # Y-axis ticks และ ticklabels ax.set(yticks=ind + width, yticklabels=np.array(['A', 'B', 'C']), ylim=[2*width - 1, len(ind)]) # Legend ขวาบน ax.legend(loc='upper right') # แสดง plot plt.show()
ผลลัพธ์
จะแสดง grouped horizontal bar chart 3 กลุ่ม แท่งส้ม (N) และน้ำเงิน (M) ติดกัน
