Reputation: 2108
I know how to make plots in matplotlib
and I know how to add a legend, such us in this example:
I want to modify the legend and show a background color for only one specific line (or component) of the legend. Taking the example of the picture, I would like the dashed red line to be shown over a yellow background (I know it is not the best choice, I am just using the colors for illustration purposes).
I know how to add a background to the entire legend box, like:
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')
But what if I want the background to highlight only one specific line/component?
Upvotes: 1
Views: 604
Reputation: 6428
The way to do this is to manipulate the handles of the legend. If I add the following code to your example I can get this to work:
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)
For more info see https://matplotlib.org/users/legend_guide.html
Upvotes: 4