Matplotlib 플롯 외부에 범례를 배치하는 방법


실제 플롯 외부에 Matplotlib 플롯의 범례를 배치하려는 경우가 종종 있습니다.

다행히도 bbox_to_anchor 인수와 결합된 matplotlib.pyplot.legend() 함수를 사용하면 쉽게 수행할 수 있습니다.

이 튜토리얼에서는 이 기능의 실제 사용에 대한 몇 가지 예를 보여줍니다.

예 1: 캡션을 오른쪽 상단에 배치

다음 코드는 Matplotlib 플롯 외부 오른쪽 상단에 범례를 배치하는 방법을 보여줍니다.

 import matplotlib.pyplot as plt

#createplot
plt. subplot (211)
plt. plot ([2, 4, 6], label=" First Data ")
plt. plot ([6, 4, 2], label=" Second Data ")

#place legend in top right corner
plt. legend (bbox_to_anchor=(1,1), loc=" upper left ")

#showplot
plt. show ()

Matplotlib 플롯 외부에 범례 배치

loc 인수는 Matplotlib에게 범례 선의 왼쪽 위 모서리를 플롯의 (1,1)의 (x,y) 좌표에 배치하도록 지시합니다.

예 2: 캡션을 오른쪽 하단에 배치

다음 코드는 Matplotlib 플롯 외부의 오른쪽 하단에 범례를 배치하는 방법을 보여줍니다.

 import matplotlib.pyplot as plt

#createplot
plt. subplot (211)
plt. plot ([2, 4, 6], label=" First Data ")
plt. plot ([6, 4, 2], label=" Second Data ")

#place legend in top right corner
plt. legend (bbox_to_anchor=(1,0), loc=" lower left ")

#showplot
plt. show () 

모서리에 있는 Matplotlib 플롯 외부의 범례

loc 인수는 Matplotlib에게 범례 선의 왼쪽 하단 모서리를 플롯의 (1,0)의 (x,y) 좌표에 배치하도록 지시합니다.

예 3: 플롯 위에 범례 배치

다음 코드는 Matplotlib 플롯 위에 범례를 배치하는 방법을 보여줍니다.

 import matplotlib.pyplot as plt

#createplot
plt. subplot (211)
plt. plot ([2, 4, 6], label=" First Data ")
plt. plot ([6, 4, 2], label=" Second Data ")

#place legend above plot
plt. legend (bbox_to_anchor=(0, 1, 1, 0), loc=" lower left ", mode=" expand ", ncol= 2 )

#showplot
plt. show () 

Matplotlib의 플롯 위에 범례 배치

mode 인수는 Matplotlib에게 범례를 플롯 길이까지 확장하도록 지시하고, ncol 인수는 Matplotlib에게 범례 레이블을 2개의 열에 배치하도록 지시합니다.

플롯 위 왼쪽 상단에 범례를 배치하려는 경우 modencol 인수를 생략할 수도 있습니다.

추가 리소스

다음 튜토리얼에서는 Matplotlib에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Matplotlib 플롯에서 글꼴 크기를 변경하는 방법
Matplotlib 플롯에서 진드기를 제거하는 방법
Matplotlib 플롯에 눈금선을 표시하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다