เพื่อเพิ่ม Colorbar ให้กับกราฟ hist2d สามารถส่งออบเจกต์ scalar mappable ที่ได้จาก hist2d เข้าไปในอาร์กิวเมนต์ของ colorbar() ได้
ขั้นตอน
- สร้างข้อมูล x, y ด้วย NumPy
- สร้าง Figure และ subplots ด้วย subplots()
- สร้างฮิสโตแกรม 2D ด้วย hist2d()
- สร้าง Colorbar จาก scalar mappable instance (ดัชนีที่ 3 ของผลลัพธ์ hist2d)
- แสดงกราฟด้วย show()
ตัวอย่างโค้ด
import numpy as np from matplotlib import pyplot as plt, colors plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.random.randn(100) y = np.random.randn(100) + 5 fig, ax = plt.subplots() hh = ax.hist2d(x, y, bins=40, norm=colors.LogNorm()) fig.colorbar(hh[3], ax=ax) plt.show()
ผลลัพธ์
