Python での修正方法: 凡例に入れるラベル付きのハンドルが見つかりません


matplotlib を使用するときに発生する可能性のある警告の 1 つは次のとおりです。

 No handles with labels found to put in legend.

この警告は通常、次の 2 つの理由のいずれかで発生します。

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 は折れ線グラフを作成しますが、 「凡例に入れるラベルを持つハンドルが見つかりません」という警告が表示されます。

この警告を回避するには、 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 は折れ線グラフを作成しますが、 「凡例に入れるラベルを持つハンドルが見つかりません」という警告が表示されます。

この警告を回避するには、プロットに行を追加した後に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 の他の一般的なエラーを修正する方法を説明します。

パンダの KeyError を修正する方法
修正方法: ValueError: float NaN を int に変換できません
修正方法: ValueError: オペランドをシェイプでブロードキャストできませんでした

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です