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

วิธีสร้าง Heatmap สีเขียว-แดงใน Python (Matplotlib)


เพื่อสร้าง Heatmap ใน Python ที่ไล่สีจากเขียวไปแดง ให้ทำตามขั้นตอน:

  • กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
  • สร้างพจนานุกรมสำหรับสีต่างๆ
  • สร้าง Colormap จากส่วนแมปปิงเชิงเส้นด้วย LinearSegmentedColormap
  • สร้างรูปและชุดซับพล็อต
  • สร้างข้อมูลสุ่มขนาด 5x5
  • สร้าง pseudocolor plot ด้วยกริดสี่เหลี่ยมไม่สม่ำเสมอ
  • สร้าง Colorbar สำหรับ ScalarMappable
  • ใช้ show() เพื่อแสดงรูป

ตัวอย่าง

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

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

cdict = {'red':   ((0.0, 0.0, 0.0),
                   (0.5, 1.0, 1.0),
                   (1.0, 1.0, 0.7)),
         'green': ((0.0, 0.7, 0.7),
                   (0.5, 1.0, 1.0),
                   (1.0, 0.0, 0.0)),
         'blue':  ((0.0, 0.0, 0.0),
                   (0.5, 1.0, 1.0),
                   (1.0, 0.0, 0.0))}

GnRd = colors.LinearSegmentedColormap('GnRd', cdict)

fig, ax = plt.subplots(1)
data = np.random.rand(5, 5)*6.-3.
p = ax.pcolormesh(data, cmap=GnRd, vmin=-5, vmax=5)
fig.colorbar(p, ax=ax)
plt.show()

ผลลัพธ์

วิธีสร้าง Heatmap สีเขียว-แดงใน Python (Matplotlib)