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

วิธีแสดงค่าเมทริกซ์และ Colormap ใน Matplotlib

ในการแสดงค่าเมทริกซ์และ colormap ใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้าง figure และชุด subplots
  • กำหนดค่า max และ min สำหรับเมทริกซ์
  • วาดค่าของเมทริกซ์ 2D หรืออาร์เรย์เป็นภาพที่เข้ารหัสสี
  • วนลูปแต่ละเซลล์ของภาพเข้ารหัสสีและวางค่าที่ตำแหน่งกึ่งกลาง
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import numpy as np
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()
min_val, max_val = 0, 5
matrix = np.random.randint(0, 5, size=(max_val, max_val))
ax.matshow(matrix, cmap='ocean')

for i in range(max_val):
    for j in range(max_val):
        c = matrix[j, i]
        ax.text(i, j, str(c), va='center', ha='center')

plt.show()

ผลลัพธ์

วิธีแสดงค่าเมทริกซ์และ Colormap ใน Matplotlibวิธีแสดงค่าเมทริกซ์และ Colormap ใน Matplotlib