Python - Matplotlib:定义单个图例条目

Python - Matplotlib: Define Individual Legend Entries

当我绘制以下内容时:

plt.plot([0,1],[0,1],'g',label='Solid')
plt.plot([0,1],[.5,1],'b',label='Solid')
plt.plot([0,1],[1,0],'g--',label='Dashed')
plt.plot([0,1],[.5,0],'b--',label='Dashed')
plt.legend()

我得到这张图片:

对我来说,图例文字太多了。有谁知道,我如何连接蓝色和绿色实线以及蓝色和绿色虚线以将图例减少为两个带有 green/blue (最好是一个在另一个之上)行和相应文本的条目? 感谢您的帮助

查看 legend() 的可能签名,即 legend(handles, labels)

Legend Tutorial中也有很好的描述。

line1,  = plt.plot([0,1],[0,1],'g',label='Solid')
line2,  = plt.plot([0,1],[.5,1],'b',label='Solid')
plt.plot([0,1],[1,0],'g--',label='Dashed')
plt.plot([0,1],[.5,0],'b--',label='Dashed')
plt.legend((line1, line2), ('green', 'blue'))
plt.show()

作为替代方案,请查看此 post 中的解决方案:

虽然有点复杂