ขั้นตอนการทำงาน
- กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
- สร้างข้อมูลสุ่ม a และ b ด้วย numpy
- สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่ด้วย figure()
- เพิ่ม axes เข้าไปใน figure ปัจจุบันเป็น subplot arrangement
- สร้าง boxplot ด้วย boxplot() พร้อม facecolor ต่างกัน
- วาง legend ด้วย legend() โดยส่ง boxplots bp1 และ bp2 พร้อมป้ายกำกับ
- ใช้เมธอด show() เพื่อแสดงรูปภาพ
ตัวอย่างโค้ด
import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True a = np.random.rand(100, 2) b = np.random.rand(100, 2) fig = plt.figure() ax = fig.add_subplot(111) bp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C0")) bp2 = ax.boxplot(a, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C2")) ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ["Box Plot 1", "Box Plot 2"], loc='upper right') plt.show()
ผลลัพธ์
