Matplotlib에서 그림을 그릴 때 legend를 바깥에 배치하고 싶을 수 있다.
이 경우에는 legend의 bbox_to_anchor를 이용하면 된다.
matplotlib 공식 문서를 보면 다음과 같이 나와있다.
설명 자체는 간단하다. 4개 원소 튜플로 넣으면 legend의 x,y,너비,높이까지 지정할 수 있다.
2개 원소 튜플로 넣으면 x,y 위치를 지정할 수 있다.
다음과 같은 그림이 있다고 하자.
import numpy as np
import matplotlib.pyplot as plt
x = np.array(range(10))
y1 = x * x
y2 = x
plt.plot(x,y1,label='quadratic function')
plt.plot(x,y2, label='linear function')
plt.legend()
plt.show()
기본적으로 legend는 location의 default 속성이 'best'로 되어있다.
만약 loc = 'lower right'이고 bbox_to_anchor=(1.0,1.0)이라면 legend의 lower right corner를 (1.0,1.0)위치에 놓고 싶다는 뜻이다.
그럼 (1.0,1.0)은 무슨 의미일까? 정확히 나와있지는 않은데 (0.5,0.5)를 figure의 중앙이라고 말하는 것을 보면 (1.0,1.0)은 그림의 오른쪽 위 corner를 의미한다.
그래서 다음과 같이 코드를 작성하면 legend가 오른쪽 위에 나타난다. 왜냐하면 legend box의 오른쪽 아래 끝을 그림의 끝에 위치하도록 했기 때문이다.
plt.plot(x,y1,label='quadratic function')
plt.plot(x,y2, label='linear function')
plt.legend(loc='lower right', bbox_to_anchor=(1.0,1.0))
plt.show()
그럼 lower right가 아닌 lower left로 하면 어떻게 될까? 왼쪽 아래 끝이 그림의 끝과 일치해야하므로 다음과 같이 된다.
그러면 다소 특이한 위치에 legend가 배치된다.
이런 원리를 이용해서 legend 위치를 마음대로 지정할 수 있다.
마지막 예시로 이렇게 바꿀 수 있다.
plt.plot(x,y1,label='quadratic function')
plt.plot(x,y2, label='linear function')
plt.legend(loc='lower left', bbox_to_anchor=(1.0,0.5))
plt.show()
이번에는 (1.0,0.5)로 지정하여 그림의 오른쪽 끝인데 y축 기준으로는 그림 중앙으로 가도록 했다.
참고자료
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
matplotlib.pyplot.legend — Matplotlib 3.6.3 documentation
Place a legend on the Axes. The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not
matplotlib.org
'프로그래밍 Programming > 파이썬 Python' 카테고리의 다른 글
[Jupyter notebook] 내가 설정한 주피터 노트북 테마 (0) | 2023.02.23 |
---|---|
[JAX] JAX 설치 및 GPU 사용하기 (2) | 2023.02.09 |
[Matplotlib] Matplotlib 폰트 스타일 바꾸기 (0) | 2023.01.13 |
[PyTorch] 특정 조건에 맞는 텐서 출력/인덱싱 등 (2) | 2023.01.08 |
[Pytorch] multi-output일 때 input gradient 구하기 (0) | 2023.01.03 |