Matplotlib 범례의 요소 순서를 변경하는 방법
다음 코드를 사용하여 Matplotlib 범례의 요소 순서를 변경할 수 있습니다.
#get handles and labels handles, labels = plt. gca (). get_legend_handles_labels () #specify order of items in legend order = [1,2,0] #add legend to plot plt. legend ([handles[idx] for idx in order],[labels[idx] for idx in order])
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Matplotlib 범례의 요소 순서 변경
Matplotlib에서 다음과 같은 선 차트를 생성한다고 가정합니다.
import pandas as pd import matplotlib. pyplot as plt #create data df = pd. DataFrame ({'points': [11, 17, 16, 18, 22, 25, 26, 24, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8], 'rebounds': [6, 8, 8, 10, 14, 12, 12, 10, 11]}) #add lines to plot plt. plot (df['points'], label='Points', color='green') plt. plot (df['assists'], label='Assists', color='steelblue') plt. plot (df['rebounds'], label='Rebounds', color='purple') #add legend plt. legend ()
범례 요소는 플롯에 선을 추가한 순서대로 배치됩니다.
그러나 다음 구문을 사용하여 범례의 요소 순서를 사용자 정의할 수 있습니다.
import pandas as pd import matplotlib. pyplot as plt #create data df = pd. DataFrame ({'points': [11, 17, 16, 18, 22, 25, 26, 24, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8], 'rebounds': [6, 8, 8, 10, 14, 12, 12, 10, 11]}) #add lines to plot plt. plot (df['points'], label='Points', color='green') plt. plot (df['assists'], label='Assists', color='steelblue') plt. plot (df['rebounds'], label='Rebounds', color='purple') #get handles and labels handles, labels = plt. gca (). get_legend_handles_labels () #specify order of items in legend order = [1,2,0] #add legend to plot plt. legend ([handles[idx] for idx in order],[labels[idx] for idx in order])
우리는 다음을 지정했습니다.
- 순서 = [1, 2, 0]
그 의미는:
- 범례의 첫 번째 항목은 원래 이전 범례의 인덱스 위치 1 에 있던 레이블(“도움말”)이어야 합니다.
- 범례의 두 번째 요소는 원래 이전 범례의 인덱스 위치 2 에 있던 레이블(“Bounces”)이어야 합니다.
- 범례의 세 번째 요소는 원래 이전 범례의 인덱스 위치 0 에 있었던 레이블(“포인트”)이어야 합니다.
추가 리소스
다음 튜토리얼에서는 Matplotlib에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Matplotlib에서 범례 위치를 변경하는 방법
Matplotlib 플롯 외부에 범례를 배치하는 방법
Matplotlib에서 범례 글꼴 크기를 변경하는 방법