Python에서 수정하는 방법: 범례에 넣을 레이블이 있는 핸들이 없습니다.
matplotlib를 사용할 때 발생할 수 있는 경고 중 하나는 다음과 같습니다.
No handles with labels found to put in legend.
이 경고는 일반적으로 다음 두 가지 이유 중 하나로 인해 발생합니다.
1. 플롯 데이터에 대한 라벨을 생성하지 못했습니다.
2. 플롯을 생성하기 전에 범례를 생성하려고 했습니다.
다음 예에서는 두 시나리오 모두에서 이 경고를 방지하는 방법을 보여줍니다.
예 1: 플롯 데이터에 대한 레이블을 생성하지 못했습니다.
matplotlib에 범례와 레이블이 있는 꺾은선형 차트를 생성하기 위해 다음 코드를 사용한다고 가정해 보겠습니다.
import matplotlib. pyplot as plt
import pandas as pd
#define data values
df = pd. DataFrame ({' x ': [18, 22, 19, 14, 14, 11, 20, 28],
' y ': [5, 7, 7, 9, 12, 9, 9, 4],
' z ': [11, 8, 10, 6, 6, 5, 9, 12]})
#add multiple lines to matplotlib plot
plt. plot (df[' x '], color=' green ')
plt. plot (df[' y '], color=' blue ')
plt. plot (df[' z '], color=' purple ')
#attempt to add legend to plot
plt. legend ()
No handles with labels found to put in legend.

Matplotlib가 선 플롯을 생성하지만 No handler with labels located to put in legend 경고가 표시됩니다.
이 경고를 방지하려면 label 인수를 사용하여 플롯의 각 라인에 대한 레이블을 제공해야 합니다.
import matplotlib. pyplot as plt
import pandas as pd
#define data values
df = pd. DataFrame ({' x ': [18, 22, 19, 14, 14, 11, 20, 28],
' y ': [5, 7, 7, 9, 12, 9, 9, 4],
' z ': [11, 8, 10, 6, 6, 5, 9, 12]})
#add multiple lines to matplotlib plot
plt. plot (df[' x '], label=' x ', color=' green ')
plt. plot (df[' y '], label=' y ', color=' blue ')
plt. plot (df[' z '], label=' z ', color=' purple ')
#attempt to add legend to plot
plt. legend ()

범례는 레이블을 사용하여 생성되며 이번에는 경고가 표시되지 않습니다.
예 2: 플롯을 생성하기 전에 범례를 생성하려고 했습니다.
matplotlib에 범례와 레이블이 있는 꺾은선형 차트를 생성하기 위해 다음 코드를 사용한다고 가정해 보겠습니다.
import matplotlib. pyplot as plt
import pandas as pd
#define data values
df = pd. DataFrame ({' x ': [18, 22, 19, 14, 14, 11, 20, 28],
' y ': [5, 7, 7, 9, 12, 9, 9, 4],
' z ': [11, 8, 10, 6, 6, 5, 9, 12]})
#attempt to add legend to plot
plt. legend ()
#add multiple lines to matplotlib plot
plt. plot (df[' x '], label=' x ', color=' green ')
plt. plot (df[' y '], label=' y ', color=' blue ')
plt. plot (df[' z '], label=' z ', color=' purple ')
No handles with labels found to put in legend.

Matplotlib가 선 플롯을 생성하지만 No handler with labels located to put in legend 경고가 표시됩니다.
이 경고를 피하려면 플롯에 라인을 추가 한 후 plt.legend()를 사용해야 합니다.
import matplotlib. pyplot as plt
import pandas as pd
#define data values
df = pd. DataFrame ({' x ': [18, 22, 19, 14, 14, 11, 20, 28],
' y ': [5, 7, 7, 9, 12, 9, 9, 4],
' z ': [11, 8, 10, 6, 6, 5, 9, 12]})
#add multiple lines to matplotlib plot
plt. plot (df[' x '], label=' x ', color=' green ')
plt. plot (df[' y '], label=' y ', color=' blue ')
plt. plot (df[' z '], label=' z ', color=' purple ')
#attempt to add legend to plot
plt. legend ()

레이블이 포함된 범례가 생성되며 이번에는 경고가 표시되지 않습니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
Pandas에서 KeyError를 수정하는 방법
수정 방법: ValueError: float NaN을 int로 변환할 수 없습니다.
해결 방법: ValueError: 피연산자를 모양과 함께 브로드캐스트할 수 없습니다.