您可以通过^{}在图例中设置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的详细信息,请参阅文档(linked here,复制如下):handletextpad : float or None
The pad between the legend handle and text. Measured in font-size
units. Default is None, which will take the value from
rcParams["legend.handletextpad"].
handlelength : float or None
The length of the legend handles. Measured in font-size units. Default
is None, which will take the value from
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()就可以得到: