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

การสร้าง Legend อัตโนมัติใน Matplotlib


เพื่อสร้าง Legend อัตโนมัติใน Matplotlib

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • กำหนดตัวแปร N สำหรับจำนวนข้อมูลตัวอย่าง
  • สร้างข้อมูล x, y, c, s ด้วย numpy
  • สร้าง figure และ subplots ด้วย subplots()
  • พลอต x และ y ด้วยสีและขนาดต่างกัน
  • วาง legend บนแกน
  • เพิ่ม artist ลงใน figure
  • สร้าง legend handles และ labels สำหรับ PathCollection
  • วาง legend อีกอันสำหรับขนาด
  • แสดงรูปด้วย show()

ตัวอย่าง

import matplotlib.pyplot as plt
import numpy as np

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

N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)

fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=c, s=s)
legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes")
ax.add_artist(legend1)
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")
plt.show()

ผลลัพธ์

การสร้าง Legend อัตโนมัติใน Matplotlib