首页 > 解决方案 > 在 matplotlib 中仅向图例的一个组件添加背景颜色

问题描述

我知道如何在其中绘制matplotlib图例,并且知道如何添加图例,例如本例中的我们:

在此处输入图像描述

我想修改图例并仅为图例的一个特定行(或组件)显示背景颜色。以图片为例,我希望红色虚线显示在黄色背景上(我知道这不是最佳选择,我只是将颜色用于说明目的)。

我知道如何为整个图例框添加背景,例如:

x = arange(0.,10,0.1)
a = cos(x)
b = sin(x)
c = exp(x/10)
d = exp(-x/10)
la = plt.plot(x,a,'b-',label='cosine')
lb = plt.plot(x,b,'r--',label='sine')
lc = plt.plot(x,c,'gx',label='exp(+x)')
ld = plt.plot(x,d,'y-', linewidth = 5,label='exp(-x)')

# Add the background to the legend
lege = plt.legend(loc="upper left", prop={'size':8})
lege.get_frame().set_facecolor('#FFFF00')

但是,如果我希望背景只突出显示一个特定的行/组件怎么办?

标签: pythonmatplotliblegend

解决方案


这样做的方法是操纵图例的句柄。如果我将以下代码添加到您的示例中,我可以让它工作:

import matplotlib.patches as mpatches
sp = plt.gca()

# Call get_legend_handles_labels()
# this returns both the handles (the lines on the left side of the legend)
# And the labels: the text in the legend
handles, labels = sp.get_legend_handles_labels()

# Let's create a yellow rectangle
yellow_patch = mpatches.Patch(color='yellow')

# Replace the second handle (for the red line)
# With a tuple; this first draws the yellow patch and then the red line
handles[1] = (yellow_patch, handles[1])
plt.legend(handles, labels)

在此处输入图像描述 有关更多信息,请参阅https://matplotlib.org/users/legend_guide.html


推荐阅读