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

วิธีจัดสีให้จุดในกราฟกระจาย (Scatterplot) ของ Matplotlib ด้วยค่าต่อเนื่อง


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูลสุ่ม x, y และ z ด้วย numpy
  • สร้าง figure และชุดของ subplots
  • สร้างกราฟกระจาย (scatter plot)
  • วาดแถบสี (colorbar) ใน axes ที่มีอยู่ โดยใช้ instance ของ scalar mappable จากจุดกระจาย
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import numpy as np
import matplotlib.pyplot as plt

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

x, y, z = np.random.rand(3, 50)
f, ax = plt.subplots()
points = ax.scatter(x, y, c=z, s=50, cmap="plasma")
f.colorbar(points)
plt.show()

ผลลัพธ์

วิธีจัดสีให้จุดในกราฟกระจาย (Scatterplot) ของ Matplotlib ด้วยค่าต่อเนื่อง