Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Histogram Matplotlib với nhiều entry legend

Để tạo legend cho histogram với nhiều màu phân đoạn, ta tô màu từng patch của histogram và tạo handles legend từ Rectangle patch.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu phân phối Rayleigh.
  • Vẽ histogram: N, bins, patches = plt.hist(data, 30, ec="k").
  • Tô màu luân phiên cho patches theo danh sách colors.
  • Tạo handles legend từ Rectangle((0,0),1,1,color=c, ec="k").
  • Gọi plt.legend(handles, labels).
  • Hiển thị bằng show().

Ví dụ

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()

Kết quả

Histogram Matplotlib với nhiều entry legend