Matplotlib 에서 플롯 외부에 범례를 배치하는 방법
 
bbox_to_anchor 를 사용하여 Matplotlib 의 플롯 외부에 범례를 배치 할 수 있습니다. bbox 는 범례를 수용하는 bounding box 를 의미합니다.
plt.legend(bbox_to_anchor=(1.05, 1))
범례는 좌표축에서(1.05, 1)위치에 배치됩니다. (0, 0)은 왼쪽 아래 모서리이고(1.0, 1.0)은 좌표축 좌표의 오른쪽 위 모서리입니다.
범례 바운딩 박스의 실제 크기와 위치는 plt.legend 에서 bbox_to_anchor 와 loc 의 4- 튜플 매개 변수로 정의됩니다.
plt.legend(bbox_to_anchor=(x0, y0, width, height), loc=)
width 와 height 는 범례 상자의 너비와 높이이고(x0, y0)은 경계 상자의 loc 좌표입니다.
loc 의 값은 다음과 같은 관계를 갖는 숫자 또는 문자열 일 수 있습니다.
| 록 번호 | 록 문자열 | 
|---|---|
| 0 | best | 
| 1 | upper right | 
| 2 | upper left | 
| 3 | lower left | 
| 4 | lower right | 
| 5 | right | 
| 6 | center left | 
| 7 | center right | 
| 8 | lower center | 
| 9 | upper center | 
| 10 | center | 
plt.legend(bbox_to_anchor=(1.05, 1.0, 0.3, 0.2), loc="upper left")
위의 코드는 범례 상자가 너비가 0.3이고 높이가 0.2 인 축 좌표(1.05, 1.0)에 위치 함을 의미합니다. 여기서(1.05, 1.0)은 상단 좌표입니다. 범례 경계 상자의 왼쪽 모서리.
bbox_to_anchor 예제
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
plt.legend(bbox_to_anchor=(1.05, 1.0), loc="upper left")
plt.tight_layout()
plt.show()

plt.tight_layout()은 그림에 서브 플로트를 잘 맞 춥니 다.
tight_layout()이 호출되지 않으면 범례 상자가 잘립니다.

범례 상자가 잘리지 않도록하는 bbox_extra_artists 및 bbox_inches
    
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
lg = plt.legend(bbox_to_anchor=(1.05, 1.0), loc="upper left")
plt.savefig(
    "example.png", dpi=300, format="png", bbox_extra_artists=(lg,), bbox_inches="tight"
)
bbox_extra_artists 는 타이트한 bbox 를 계산할 때 고려할 Artist의 목록을 지정합니다.
bbox_inches 가 tight 로 설정되면, 그림의 단단한 bbox 를 알아낼 것입니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook