Matplotlib에서 수동 범례를 만드는 방법(예제 포함)


matplotlib.linesmatplotlib.patches 하위 모듈의 기능을 사용하여 matplotlib 플롯에 수동 범례를 만들 수 있습니다.

다음 예에서는 이를 수행하는 방법을 보여줍니다.

예: Matplotlib에서 수동 범례 만들기

다음 코드는 기본 범례를 사용하여 matplotlib에서 산점도를 생성하는 방법을 보여줍니다.

 import matplotlib. pyplot as plt

#define data to plot
x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 5, 8, 12, 18, 27]

#create scatter plot of x vs. y
plt. scatter (x, y, label=' Original Data ', color=' steelblue ')

#add legend
plt. legend ()

#displayplot
plt. show () 

사용자 지정 선과 사각형이 포함된 수동 범례를 만들려면 matplotlib.linesmatplotlib.patches 하위 모듈을 가져와야 합니다.

다음 코드는 이러한 하위 모듈을 사용하여 수동 범례를 만드는 방법을 보여줍니다.

 import matplotlib. pyplot as plt
from matplotlib. lines import Line2D
import matplotlib. patches as mpatches

#define data to plot
x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 5, 8, 12, 18, 27]

#create scatter plot of x vs. y
plt. scatter (x, y, label=' Original Data ', color=' steelblue ')

#define handles and labels that will get added to legend
handles, labels = plt. gca (). get_legend_handles_labels ()

#define patches and lines to add to legend
patch1 = mpatches. Patch (color=' orange ', label=' First Manual Patch ')
patch2 = mpatches. Patch (color=' orange ', label=' First Manual Patch ')   
line1 = Line2D([0], [0], label=' First Manual Line ', color=' purple ')
line2 = Line2D([0], [0], label=' Second Manual Line ', color=' red ')

#add handles
handles. extend ([patch1, line1, line2])

#add legend
plt. legend (handles=handles)

#displayplot
plt. show () 

Matplotlib 매뉴얼 범례

이 범례에는 원본 데이터의 레이블뿐만 아니라 수동으로 추가한 요소의 레이블과 모양도 포함되어 있습니다.

요소의 레이블이나 색상을 변경하려면 이전 코드 부분의 레이블색상 인수 값을 변경하면 됩니다.

참고 : 플롯에서 범례의 위치를 변경하는 방법을 알아보려면 이 튜토리얼을 참조하십시오.

추가 리소스

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

Matplotlib에서 플롯 크기를 늘리는 방법
Matplotlib에서 제목 위치를 조정하는 방법
Matplotlib에서 축 범위를 설정하는 방법

의견을 추가하다

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