Jav*_*ner 13 python plot matplotlib legend figure
我想在图例中显示行标签的文本,但也不是一行(如下图所示):

我试图最小化图例的线条和标签,并且也只覆盖新标签(如下面的代码所示).但是,这个传奇带来了两个回归.
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')
Run Code Online (Sandbox Code Playgroud)
tsa*_*ndo 13
我发现了另一个更简单的解决方案 - 只需在图例属性中将标记的比例设置为零:
plt.legend(markerscale=0)
Run Code Online (Sandbox Code Playgroud)
当您不希望标记在视觉上误认为是真正的数据点(甚至是异常值!)时,这在散点图中特别有用.
tsh*_*wen 13
您可以通过如下所示在图例中设置handletextpad和:handlelengthlegend_handler
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)
Run Code Online (Sandbox Code Playgroud)
详细信息handletextpad并handlelength在文档中(链接在这里,并在下面复制):
handletextpad:float或None
图例句柄和文本之间的垫.以字体大小单位测量.默认值为None,它将取rcParams [ "legend.handletextpad" ]中的值.
handlelength:float或None
图例处理的长度.以字体大小单位测量.默认值为None,它将取rcParams ["legend.handlelength"]中的值.
使用上面的代码:
使用一些额外的线条,标签可以与其线条具有相同的颜色.只需使用.set_color()via 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] )
Run Code Online (Sandbox Code Playgroud)
只是打电话plt.legend()给:
那时,它可以说更容易使用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()
Run Code Online (Sandbox Code Playgroud)

但是,如果您确实想要使用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()
Run Code Online (Sandbox Code Playgroud)
