如何只在图例中显示文本标签?(即去除图例中的线条)
我想在图例中只显示一条线的标签文字,而不显示这条线本身(如下图所示):
我试着把图例中的线和标签都缩小,只保留新的标签(如下方的代码所示)。但是,图例还是把线也显示出来了。
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')
5 个回答
0
如果你想要自定义图例,也要加上lw=0这个设置。
p5 = mpatches.Patch(color="green", label="r={}".format(cor_rh), lw=0)
p6 = mpatches.Patch(color=p1.get_color(), label="t={}".format(rh_trend), lw=0)
p7 = mpatches.Patch(color=p3.get_color(), label="t={}".format(hx_trend), lw=0)
ln1 = [p5,p6,p7]
host.legend(handles=ln1, loc=1, labelcolor='linecolor, handlelength=0)
7
这里推荐一个简单又有效的解决办法:handlelength=0
。举个例子,你可以这样写:ax.legend(handlelength=0)
。
23
你可以通过下面的代码在图例中设置 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)
关于 handletextpad
和 handlelength
的详细信息可以在文档中找到(这里有链接,也在下面复制了):
handletextpad : 浮点数或 None
这是图例的图标和文字之间的间距。单位是字体大小。默认值是 None,这样会使用 rcParams["legend.handletextpad"] 中的值。
handlelength : 浮点数或 None
这是图例图标的长度。单位也是字体大小。默认值是 None,这样会使用 rcParams["legend.handlelength"] 中的值。
使用上面的代码:
再加几行代码,标签就可以和它们的线条颜色一致。只需通过 legend.get_texts()
使用 .set_color()
方法即可。
# 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] )
只调用 plt.legend()
就会得到:
23
我找到了一种更简单的解决办法——只需在图例属性中把标记的缩放设置为零:
plt.legend(markerscale=0)
这在散点图中特别有用,因为你不想让标记看起来像真实的数据点(甚至是异常值!)。
26
在这种情况下,直接使用 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()
不过,如果你真的想用 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()