Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Biểu đồ cột xếp chồng ngang (Horizontal stacked bar chart) trong Matplotlib

Để vẽ biểu đồ cột xếp chồng ngang trong Matplotlib, ta dùng barh().

Các bước

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Tạo danh sách years, issues_addressed, issues_pending theo năm.
  • Vẽ cột ngang với years, issues_addressed.
  • Tạo cột chồng ngang bằng barh() với left=issues_addressed.
  • Đặt legend.
  • Hiển thị hình bằng show().

Ví dụ

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
year = [2014, 2015, 2016, 2017, 2018, 2019]
issues_addressed = [10, 14, 0, 10, 15, 15]
issues_pending = [5, 10, 50, 2, 0, 10]
b1 = plt.barh(year, issues_addressed, color="red")
b2 = plt.barh(year, issues_pending, left=issues_addressed, color="yellow")
plt.legend([b1, b2], ["Completed", "Pending"], title="Issues", loc="upper right")
plt.show()

Kết quả

Biểu đồ cột xếp chồng ngang (Horizontal stacked bar chart) trong Matplotlib