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

Scatter Plot หลายค่า Y ต่อค่า X เดียวใน Python Matplotlib

เมื่อมีหลายค่า Y สำหรับ X เดียว ใช้ zip() รวม x และ y แล้ววนลูปพลอตแต่ละคู่ด้วย plt.scatter() วิธีนี้เหมาะสำหรับข้อมูลที่ไม่ได้อยู่ในรูปแบบอาร์เรย์ 2 มิติปกติ

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

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้างข้อมูล xs และ ys แบบสุ่ม
  3. ใช้ zip(xs, ys) รวมคู่แล้ววนลูป
  4. พลอตแต่ละจุดด้วย plt.scatter(x, y)
  5. แสดงผล

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

import numpy as np
from matplotlib import pyplot as plt

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

xs = np.random.rand(100)
ys = np.random.rand(100)

for x, y in zip(xs, ys):
    plt.scatter(x, y, cmap="copper")

plt.show()

ผลลัพธ์

Scatter Plot หลายค่า Y ต่อค่า X เดียวใน Python Matplotlib