web-dev-qa-db-ja.com

プロットの凡例にテキストラベルを表示するにはどうすればよいですか? (例:凡例のラベルの行を削除する)

凡例に行のラベルのテキストを表示したいが、行も表示したくない(下の図に示すように):

enter image description here

凡例の行とラベルを最小化し、新しいラベルのみを上書きしようとしました(以下のコードのように)。しかし、伝説は両方を取り戻します。

    legend = ax.legend(loc=0, shadow=False) 
    for label in legend.get_lines(): 
        label.set_linewidth(0.0) 
    for label in legend.get_texts(): 
        label.set_fontsize(0) 

    ax.legend(loc=0, title='New Title')
15
Java.beginner

その時点で、 annotate を使用する方が間違いなく簡単です。

例えば:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(0, 1, 1000).cumsum()

fig, ax = plt.subplots()
ax.plot(data)
ax.annotate('Label', xy=(-12, -12), xycoords='axes points',
            size=14, ha='right', va='top',
            bbox=dict(boxstyle='round', fc='w'))
plt.show()

enter image description here

ただし、legendを使用したい場合は、次のようにします。サイズを0に設定してパディングを削除することに加えて、凡例ハンドルを明示的に非表示にする必要があります。

import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(0, 1, 1000).cumsum()

fig, ax = plt.subplots()
ax.plot(data, label='Label')

leg = ax.legend(handlelength=0, handletextpad=0, fancybox=True)
for item in leg.legendHandles:
    item.set_visible(False)
plt.show()

enter image description here

7
Joe Kington

私は別のはるかに簡単な解決策を見つけました-凡例のプロパティでマーカーのスケールをゼロに設定するだけです:

plt.legend(markerscale=0)

これは、マーカーが実際のデータポイント(または外れ値)と視覚的に間違えられたくない場合の散布図で特に役立ちます。

12
tsando

以下に示すように、 _legend_handler_ を使用して、凡例にhandletextpadおよびhandlelengthを設定するだけです。

_import matplotlib.pyplot as plt
import numpy as np
# Plot up a generic set of lines
x = np.arange( 3 )
for i in x:
    plt.plot( i*x, x, label='label'+str(i), lw=5 )
# Add a legend 
# (with a negative gap between line and text, and set "handle" (line) length to 0)
legend = plt.legend(handletextpad=-2.0, handlelength=0)
_

handletextpadhandlelengthの詳細は、ドキュメントにあります( ここにリンク 、以下にコピー):

handletextpad:floatまたはNone

凡例ハンドルとテキストの間のパッド。フォントサイズ単位で測定されます。デフォルトはNoneで、rcParams [ "legend.handletextpad"]から値を取得します。

handlelength:floatまたはNone

凡例ハンドルの長さ。フォントサイズ単位で測定されます。デフォルトはNoneで、rcParams ["legend.handlelength"]から値を取得します。

上記のコードで:

enter image description here

いくつかの追加の線で、ラベルはその線と同じ色を持つことができます。 .set_color()を介してlegend.get_texts()を使用するだけです。

_# Now color the legend labels the same as the lines
color_l = ['blue', 'orange', 'green']
for n, text in enumerate( legend.texts ):
    print( n, text)
    text.set_color( color_l[n] )
_

enter image description here

plt.legend()を呼び出すだけで、次のようになります。

enter image description here

12
tsherwen

ベストアンサーを提案:_handlelength=0_、例:ax.legend(handlelength=0)

0
Ji Ma