[Matplotlib] legend 그림 바깥에 배치/원하는 위치에 배치

2023. 1. 14. 22:46·프로그래밍 Programming/파이썬 Python

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
'프로그래밍 Programming/파이썬 Python' 카테고리의 다른 글
  • [Jupyter notebook] 내가 설정한 주피터 노트북 테마
  • [JAX] JAX 설치 및 GPU 사용하기
  • [Matplotlib] Matplotlib 폰트 스타일 바꾸기
  • [PyTorch] 특정 조건에 맞는 텐서 출력/인덱싱 등
보통의공대생
보통의공대생
수학,프로그래밍,기계항공우주 등 공부하는 기록들을 남깁니다.
  • 보통의공대생
    뛰는 놈 위에 나는 공대생
    보통의공대생
  • 전체
    오늘
    어제
    • 분류 전체보기 (460)
      • 공지 (1)
      • 영어 공부 English Study (40)
        • 텝스 TEPS (7)
        • 글 Article (21)
        • 영상 Video (10)
      • 연구 Research (99)
        • 최적화 Optimization (3)
        • 데이터과학 Data Science (7)
        • 인공지능 Artificial Intelligent (40)
        • 제어 Control (45)
      • 프로그래밍 Programming (103)
        • 매트랩 MATLAB (25)
        • 파이썬 Python (33)
        • 줄리아 Julia (2)
        • C++ (3)
        • 리눅스 우분투 Ubuntu (6)
      • 항공우주 Aeronautical engineeri.. (21)
        • 항법 Navigation (0)
        • 유도 Guidance (0)
      • 기계공학 Mechanical engineering (13)
        • 열역학 Thermodynamics (0)
        • 고체역학 Statics & Solid mechan.. (10)
        • 동역학 Dynamics (1)
        • 유체역학 Fluid Dynamics (0)
      • 수학 Mathematics (34)
        • 선형대수학 Linear Algebra (18)
        • 미분방정식 Differential Equation (3)
        • 확률및통계 Probability & Sta.. (2)
        • 미적분학 Calculus (1)
        • 복소해석학 Complex Analysis (5)
        • 실해석학 Real Analysis (0)
      • 수치해석 Numerical Analysis (21)
      • 확률 및 랜덤프로세스 Random process (2)
      • 추론 & 추정 이론 Estimation (3)
      • 기타 (26)
        • 설계 프로젝트 System Design (8)
        • 논문작성 Writing (55)
        • 세미나 Seminar (2)
        • 생산성 Productivity (3)
      • 유학 생활 Daily (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    고체역학
    LaTeX
    서버
    옵시디언
    Numerical Analysis
    Julia
    논문작성법
    Python
    JAX
    딥러닝
    Zotero
    Statics
    MATLAB
    IEEE
    Linear algebra
    수치해석
    생산성
    우분투
    텝스공부
    teps
    인공지능
    obsidian
    pytorch
    에러기록
    WOX
    논문작성
    텝스
    Dear abby
    ChatGPT
    matplotlib
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
보통의공대생
[Matplotlib] legend 그림 바깥에 배치/원하는 위치에 배치
상단으로

티스토리툴바