Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การตั้งค่าสีพื้นหลังคอลัมน์ใน Matplotlib Table

ใช้ ax.table() พร้อมพารามิเตอร์ cellColours เพื่อกำหนดสีแต่ละ Cell/Column

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. กำหนด Columns, Cell Text, และ Colors
  3. สร้าง Figure และ Axes
  4. สร้าง Table พร้อม Cell Colours
  5. ปิด Axis
  6. แสดงผล

ตัวอย่างโค้ด


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"]
]

# สีแต่ละ Cell: [Row1_Colors, Row2_Colors]
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()

การปรับแต่ง Table เพิ่มเติม


# ปรับขนาด Font
the_table.auto_set_font_size(False)
the_table.set_fontsize(12)

# ปรับ Column Width
the_table.auto_set_column_width([0, 1, 2, 3])

# สไตล์ Header
for (row, col), cell in the_table.get_celld().items():
    if row == 0:  # Header row
        cell.set_text_props(weight='bold', color='white')
        cell.set_facecolor('navy')

ผลลัพธ์

ตาราง 2 แถว 4 คอลัมน์ แต่ละ Cell มีสีพื้นหลังตามที่กำหนด Column 1=Red/Blue, Column 2=Yellow/Green, etc.