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

การเปลี่ยนความโปร่งใส/ความทึบของตารางใน Matplotlib

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots

  • สร้าง Figure และชุด Subplots

  • สร้างข้อมูลสุ่มขนาด 10×3

  • สร้าง Tuple ของชื่อคอลัมน์

  • ซ่อนเครื่องหมายแกนด้วย axis('off')

  • สร้างตารางด้วยข้อมูลและชื่อคอลัมน์

  • วนลูปแต่ละเซลล์ เปลี่ยนความโปร่งใสด้วย set_alpha()

  • แสดงรูปภาพด้วยเมธอด show()

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

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, axs = plt.subplots(1, 1)
data = np.random.random((10, 3))
columns = ("Column I", "Column II", "Column III")

axs.axis('off')
the_table = axs.table(cellText=data, colLabels=columns, loc='center')

for k, cell in the_table._cells.items():
    cell.set_edgecolor('black')
    if k[0] == 0 or k[1] < 0:  # Header row
        cell.set_text_props(weight='bold', color='w')
        cell.set_facecolor('red')
        cell.set_alpha(0.5)
    else:
        cell.set_facecolor(['green', 'yellow'][k[0] % 2])
        cell.set_alpha(0.5)

plt.show()

ผลลัพธ์

ตารางที่มีเซลล์ส่วนหัวสีแดงตัวอักษรขาว ตัวอักษรหนา ความโปร่งใส 0.5 ส่วนเนื้อหาสลับสีเขียว/เหลือง ความโปร่งใส 0.5 เช่นกัน

หมายเหตุ: ค่า alpha 0 = โปร่งใสสมบูรณ์, 1 = ทึบสมบูรณ์ การเข้าถึง _cells เป็นการเข้าถึง attribute ภายใน (private) อาจเปลี่ยนในเวอร์ชันอนาคต