你如何在情节传奇中显示文字标签? (例如,删除图例中的标签行)

时间:2014-08-04 16:17:44

标签: python matplotlib plot legend figure

我想在图例中显示行标签的文字,但也不是一行(如下图所示):

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')

4 个答案:

答案 0 :(得分:11)

我找到了另一个更简单的解决方案 - 只需在图例属性中将标记的比例设置为零:

plt.legend(markerscale=0)

当您不希望标记在视觉上被误认为是真正的数据点(甚至是异常值!)时,这在散点图中特别有用。

答案 1 :(得分:11)

您可以通过legend_handler在图例中设置handletextpadhandlelength,如下所示:

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上的详情位于文档(linked here,并在下方复制):

  

handletextpad :float或None

     

图例句柄和文本之间的填充。以字体大小测量   单位。默认值为None,将从中获取值   rcParams [" legend.handletextpad" ]。

     

handlelength :float或None

     

图例处理的长度。以字体大小单位测量。默认   是None,它将取值   rcParams [" legend.handlelength&#34]。

使用上面的代码:

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

答案 2 :(得分:7)

此时,使用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

答案 3 :(得分:3)

建议最佳答案:handlelength=0,例如:ax.legend(handlelength=0)