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

วิธีสร้างตำนาน (Legend) สำหรับแท่ง 3D ใน Matplotlib

เนื่องจาก bar3d ไม่รองรับ legend โดยตรง ให้สร้าง proxy artist ด้วย plt.Rectangle แล้วส่งเข้า ax.legend() พร้อมป้ายกำกับ

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

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้าง figure และ axes 3D
  3. พลอตชุดแท่งแรก สร้าง Rectangle proxy สีเขียว
  4. พลอตชุดแท่งที่สอง สร้าง Rectangle proxy สีแดง
  5. สร้าง legend จาก proxy artists
  6. แสดงผล

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

import numpy as np
from matplotlib import pyplot as plt

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

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')

x3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y3 = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z3 = np.zeros(10)
dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ax1.bar3d(x3, y3, z3, dx, dy, dz, color="green")
b1 = plt.Rectangle((0, 0), 1, 1, fc="green")

ax1.bar3d(y3, x3, z3, dx, dy, dz, color="red")
b2 = plt.Rectangle((0, 0), 1, 1, fc="red")

ax1.legend([b1, b2], ['type1', 'type2'])
plt.show()

ผลลัพธ์

วิธีสร้างตำนาน (Legend) สำหรับแท่ง 3D ใน Matplotlib