โดยใช้ Pandas เราสามารถสร้าง DataFrame และสร้างตัวแปร Figure และ Axes ด้วยเมธอด subplot() หลังจากนั้น เราสามารถใช้เมธอด ax.scatter() เพื่อได้กราฟที่ต้องการ
ขั้นตอน
สร้างลิสต์จำนวนนักเรียน
สร้างลิสต์คะแนนที่นักเรียนได้รับ
เพื่อแสดงสีของแต่ละจุดกระจาย เราสามารถมีลิสต์สีได้
ใช้ Pandas สร้างลิสต์แทนแกนของ DataFrame
สร้างตัวแปร fig และ ax ด้วยเมธอด subplots โดยค่าเริ่มต้น nrows และ ncols เป็น 1
ตั้งค่าป้ายกำกับ "Students count" ด้วย
plt.xlabel()ตั้งค่าป้ายกำกับ "Obtained marks" ด้วย
plt.ylabel()สร้างจุดกระจาย (scatter) โดยใช้ DataFrame จากขั้นตอนที่ 4 จุดคือ students_count, marks และ color
ใช้
plt.show()เพื่อแสดงกราฟ
ตัวอย่าง
from matplotlib import pyplot as plt
import pandas as pd
no_of_students = [1, 2, 3, 5, 7, 8, 9, 10, 30, 50]
marks_obtained_by_student = [100, 95, 91, 90, 89, 76, 55, 10, 3, 19]
color_coding = ['red', 'blue', 'yellow', 'green', 'red', 'blue', 'yellow', 'green', 'yellow', 'green']
df = pd.DataFrame(dict(students_count=no_of_students, marks=marks_obtained_by_student, color=color_coding))
fig, ax = plt.subplots()
plt.xlabel('Students count')
plt.ylabel('Obtained marks')
ax.scatter(df['students_count'], df['marks'], c=df['color'])
plt.show()
ผลลัพธ์
