Giới thiệu
Matplotlib cho phép thêm nhiều hơn một biểu đồ (plot) vào cùng một hình vẽ (figure). Hướng dẫn này trình bày cách hiển thị dữ liệu trên cùng một biểu đồ, trên hai trục tọa độ khác nhau.
Cách thực hiện
1. Cài đặt matplotlib
pip install matplotlib
Import thư viện:
import matplotlib.pyplot as plt
2. Chuẩn bị dữ liệu
# Dữ liệu mẫu (giả định, không chính xác)
mobile = ['Iphone', 'Galaxy', 'Pixel']
# Dữ liệu bán hàng theo 4 quý (triệu đơn vị)
units_sold = (
('2016', 12, 8, 6),
('2017', 14, 10, 7),
('2018', 16, 12, 8),
('2019', 18, 14, 10),
('2020', 20, 16, 5),
)
3. Tách dữ liệu thành mảng cho từng hãng
# Tách dữ liệu
Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)
# Vị trí các cột
Position = list(range(len(units_sold)))
# Độ rộng cột
Width = 0.2
4. Tạo subplot đầu tiên (hàng 1, cột 1)
plt.subplot(2, 1, 1)
5. Vẽ biểu đồ cột cho doanh số iPhone
Iphone = plt.bar(Position, IPhone_Sales, color='green')
plt.ylabel('Doanh số iPhone')
plt.xticks(Position, Years)
6. Tạo trục Y thứ hai (twinx) cho doanh số Samsung Galaxy
plt.twinx()
Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')
plt.ylabel('Doanh số Galaxy')
plt.xticks(Position, Years)
7. Vẽ biểu đồ đường cho Google Pixel (subplot thứ 2)
plt.subplot(2, 1, 2)
plt.plot(Position, Pixel_Sales, color='yellow')
plt.ylabel('Doanh số Pixel')
plt.gca().set_ylim(ymin=0)
plt.xticks(Position, Years)
8. Chương trình hoàn chỉnh và lưu biểu đồ
import matplotlib.pyplot as plt
# Dữ liệu
mobile = ['Iphone', 'Galaxy', 'Pixel']
units_sold = (
('2016', 12, 8, 6),
('2017', 14, 10, 7),
('2018', 16, 12, 8),
('2019', 18, 14, 10),
('2020', 20, 16, 5),
)
# Tách dữ liệu
Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)
Position = list(range(len(units_sold)))
Width = 0.2
# Subplot 1: iPhone (cột) + Galaxy (đường) trên 2 trục Y
plt.subplot(2, 1, 1)
Iphone = plt.bar(Position, IPhone_Sales, color='green')
plt.ylabel('Doanh số iPhone')
plt.xticks(Position, Years)
plt.twinx()
Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')
plt.ylabel('Doanh số Galaxy')
plt.xticks(Position, Years)
# Subplot 2: Pixel
plt.subplot(2, 1, 2)
plt.plot(Position, Pixel_Sales, color='yellow')
plt.ylabel('Doanh số Pixel')
plt.gca().set_ylim(ymin=0)
plt.xticks(Position, Years)
# Lưu file
plt.savefig('CombiningGraphs.png', dpi=72)
# plt.show()