Để đặt màu nền (background color) cho cột trong bảng (table) Matplotlib:
- Thiết lập kích thước figure và padding
- Tạo tuple cho thuộc tính
columns - Tạo list of lists: dữ liệu bản ghi
- Tạo list of lists: màu từng cell
- Tạo figure và subplots
- Thêm table vào axes
ax - Tắt axes
- Hiển thị bằng
show()
Ví dụ mã nguồn
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ('name', 'age', 'marks', 'salary')
cell_text = [["John", "23", "98", "234"], ["James", "24", "90", "239"]]
colors = [["red", "yellow", "blue", "green"], ["blue", "green", "yellow", "red"]]
fig, ax = plt.subplots()
the_table = ax.table(cellText=cell_text, cellColours=colors, colLabels=columns, loc='center')
ax.axis('off')
plt.show()
Kết quả
Bảng 2 hàng x 4 cột, mỗi ô có màu nền khác nhau theo ma trận colors.

Tham số table: cellText, cellColours, colLabels, rowLabels, colWidths, loc. Dùng cellLoc='center' căn giữa text.