I would like to make a legend entry in a matplotlib look something like this:
It has multiple colors for a given legend item. Code is shown below which outputs a red rectangle. I'm wondering what I need to do to overlay one color ontop of another? Or is there a better solution?
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='Foo')
plt.legend(handles=[red_patch])
plt.show()
The solution I am proposing is to combine two different proxy-artists for one entry legend, as described here: Combine two Pyplot patches for legend.
The strategy is then to set the
fillstyle
of the first square marker toleft
while the other one is set toright
(see http://matplotlib.org/1.3.0/examples/pylab_examples/filledmarker_demo.html). Two different colours can then be attributed to each marker in order to produce the desired two-colour legend entry.The code below show how this can be done. Note that the
numpoints=1
argument inplt.legend
is important in order to display only one marker for each entry.Which results in:
Disclaimer: This will only work for a two-colors legend entry. If more than two colours is desired, I cannot think of any other way to do this other than the approach described by @jwinterm (Python Matplotlib Multi-color Legend Entry)
Probably not exactly what you're looking for, but you can do it (very) manually by placing patches and text yourself on the plot. For instance: