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

Matplotlib Histogram พร้อม Legend หลายรายการ


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูลสุ่มด้วย numpy
  • พล็อตฮิสโตแกรมด้วย hist()
  • สร้างรายการสีสำหรับทาสีหน้าของแต่ละ patch
  • วนลูป patches ตั้งค่า face color แต่ละ patch
  • สร้างรายการ handles สำหรับ legend
  • ใช้ legend() สำหรับ legend หลายรายการ
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

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

data = np.random.rayleigh(size=1000) * 35
N, bins, patches = plt.hist(data, 30, ec="k")
colors = ["red", "yellow", "green"]
for i in range(0, len(bins)-1):
    patches[i].set_facecolor(colors[i % len(colors)])
handles = [Rectangle((0, 0), 1, 1, color=c, ec="k") for c in colors]
labels = ["Red", "Yellow", "Green"]
plt.legend(handles, labels)
plt.show()

ผลลัพธ์

Matplotlib Histogram พร้อม Legend หลายรายการ