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

วิธีกำหนดสีเฉพาะให้เซลล์เฉพาะใน Matplotlib Table

การระบุสีพื้นหลังเซลล์แต่ละเซลล์ใน Table

ใช้ parameter cellColours (list of lists) ใน ax.table()

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • กำหนด columns tuple
  • เตรียม cell_text (list of lists) และ colors (list of lists สีแต่ละเซลล์)
  • สร้าง figure และ axes
  • เพิ่ม table ด้วย ax.table(cellText=..., cellColours=..., colLabels=..., loc='center')
  • ปิด axes
  • แสดงผลด้วย show()

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

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()

คำอธิบาย

cellColours ต้องมีขนาดเท่ากับ cellText (rows x cols) รวม header row ด้วยถ้ามี colLabels