Reputation: 311
I want to shade around the line in a legend, like in the picture below.
I tried using 'hatch' with something like the following:
handles, labels = ax0.get_legend_handles_labels()
handles[0] = mpatches.Patch(facecolor='red', edgecolor='red', alpha=1.0, linewidth=0, label="Theory (MLL)", hatch='-')
handles[i].set_facecolor('pink')
first_legend = ax0.legend(handles, labels, loc=0, frameon=0, borderpad=0.1)
ax = ax0.add_artist(first_legend)
But this causes the rectangle to have multiple lines like the following:
Upvotes: 4
Views: 1887
Reputation: 3972
You can plot two handles on top of one another by putting them together in a tuple (see the bit about HandlerTuple in this guide: http://matplotlib.org/users/legend_guide.html). In addition to that, to get the line to extend to the edge of the patch, you can use a custom version of the normal line handler with marker_pad = 0
.
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerLine2D
import numpy as np
line, = plt.plot(range(10), color = 'red')
patch = mpatches.Patch(facecolor='pink', alpha=1.0, linewidth=0)
plt.legend([(patch, line)], ["Theory"], handler_map = {line : HandlerLine2D(marker_pad = 0)} )
plt.show()
Upvotes: 6