Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Matplotlib에서 자동화된 범례 생성

<시간/>

Matplotlib에서 범례 생성을 자동화하기 위해 다음 단계를 수행할 수 있습니다. -

  • 그림 크기를 설정하고 서브플롯 사이 및 주변 여백을 조정합니다.
  • 변수 초기화, N, 샘플 데이터의 수에 대해.
  • x, y, c 생성 및 numpy를 사용한 데이터.
  • subplots()를 사용하여 그림과 서브플롯 세트 생성 방법.
  • 플롯 xy 다양한 색상과 크기의 데이터 포인트
  • 축에 범례를 배치합니다.
  • 아티스트 추가 그림에.
  • PathCollection에 대한 범례 핸들 및 레이블을 만듭니다.
  • 다시, 크기에 대한 축에 범례를 배치합니다.
  • 그림을 표시하려면 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()

출력

Matplotlib에서 자동화된 범례 생성