Để vẽ nhiều thanh ngang trên một biểu đồ với matplotlib, thực hiện các bước sau:
Các bước
- Nhập pandas, matplotlib, numpy.
- Thiết lập kích thước hình và padding.
- Tạo mảng vị trí thanh ngang.
- Khởi tạo biến width độ rộng thanh.
- Tạo horizontal bar plot.
- Đặt ticks và ticklabels trục Y với giới hạn.
- Đặt legend vị trí upper right.
- Hiển thị hình bằng show().
Ví dụ
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() 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') ax.set(yticks=ind + width, yticklabels=np.array(['A', 'B', 'C']), ylim=[2*width - 1, len(ind)]) ax.legend(loc='upper right') plt.show()
Kết quả
Biểu đồ thanh ngang nhóm (grouped horizontal bar chart) 3 nhóm A,B,C, mỗi nhóm 2 thanh cam và xanh.