Python Matplotlib Multicolor Legend

I would like to record a legend in matplotlib to look something like this:

enter image description here

It has several colors for this legend object. Below is a code that displays a red rectangle. I am wondering what I need to do to apply one color to 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() 
+6
source share
2 answers

The solution I propose is to combine two different proxy-artists for one record, as described here: Combine two Pyplot patches for the legend .

Then the strategy should set the fillstyle first square marker to left and the other to right (see http://matplotlib.org/1.3.0/examples/pylab_examples/filledmarker_demo.html ). Then, for each marker, two different colors can be assigned to create the desired two-color title.

The code below shows how to do this. Note that the numpoints=1 argument in plt.legend important to display only one marker for each entry.

 import matplotlib.pyplot as plt plt.close('all') #---- Generate a Figure ---- fig = plt.figure(figsize=(4, 4)) ax = fig.add_axes([0.15, 0.15, 0.75, 0.75]) ax.axis([0, 1, 0, 1]) #---- Define First Legend Entry ---- m1, = ax.plot([], [], c='red' , marker='s', markersize=20, fillstyle='left', linestyle='none') m2, = ax.plot([], [], c='blue' , marker='s', markersize=20, fillstyle='right', linestyle='none') #---- Define Second Legend Entry ---- m3, = ax.plot([], [], c='cyan' , marker='s', markersize=20, fillstyle='left', linestyle='none') m4, = ax.plot([], [], c='magenta' , marker='s', markersize=20, fillstyle='right', linestyle='none') #---- Plot Legend ---- ax.legend(((m2, m1), (m3, m4)), ('Foo', 'Foo2'), numpoints=1, labelspacing=2, loc='center', fontsize=16) plt.show(block=False) 

Result:

enter image description here

Disclaimer:. This will work only for recording with two colors. If more than two colors are required, I cannot think of any other way to do this except the approach described in @jwinterm ( Python Matplotlib Multi-Color Legend Entry )

+2
source

Probably not quite what you are looking for, but you can do it (very) manually by placing patches and text on the chart. For instance:

 import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() red_patch = mpatches.Patch(color='red', label='Foo') plt.legend(handles=[red_patch]) r1 = mpatches.Rectangle((0.1, 0.1), 0.18, 0.1, fill=False) r2 = mpatches.Rectangle((0.12, 0.12), 0.03, 0.06, fill=True, color='red') r3 = mpatches.Rectangle((0.15, 0.12), 0.03, 0.06, fill=True, color='blue') ax.add_patch(r1) ax.add_patch(r2) ax.add_patch(r3) ax.annotate('Foo', (0.2, 0.13), fontsize='x-large') plt.show() 
0
source

All Articles