Search code examples
pythonmatplotliblegend

Matplotlib does not display the hatch of a patch in a legend


I'm not sure if this is a bug or I'm doing something wrong. My goal is to display a hatch in the legend but it does not work. The code I use for that is

import matplotlib.patches as mpatches
...
def plot_legend(ax):
    ep = mpatches.Patch(color=[1.0, 0.5, 1.0, 1], hatch='/',
        label=r'$\pi_e\ free$')
    cp = mpatches.Patch(color=[1.0, 1.0, 1.0, 1], label='$\pi_e = exp(-60)$')
    #ax.legend(handles=[ep, cp], bbox_to_anchor=(1.05, 1), 
    #    loc=2, borderaxespad=0.)

    pyl.legend(handles=[ep, cp],
         loc=1)

    return

The results is the following:

The weird color in the legend is to show that is working.

The version of matplotlib I'm using is 1.5.1 in a mac computer.


Solution

  • Presumably the color keyword in mpatches.Patch() is being applied for both edgecolor and facecolor. Your hatch might be there, just not visible because of the same color.

    Explicitly specifying the facecolor should solve your problem:

    ep = mpatches.Patch(edgecolor=[1.0, 0.5, 1.0, 1],
                        facecolor=[0.5, 1.0, 1.0, 1],
                        hatch='/', label=r'$\pi_e\ free$')