Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal layout of patches in legend (matplotlib)

I create legend in my chart this way:

legend_handles.append(matplotlib.patches.Patch(color=color1, label='group1'))
legend_handles.append(matplotlib.patches.Patch(color=color2, label='group2'))
ax.legend(loc='upper center', handles=legend_handles, fontsize='small')

This results in the legend items stacked vertically (top-bottom), while I would like to put them horizontally left to right.

How can I do that?

(matplotlib v1.4.3)

like image 768
LetMeSOThat4U Avatar asked Sep 09 '16 11:09

LetMeSOThat4U


People also ask

How to show legend elements horizontally in Matplotlib?

How to show legend elements horizontally in Matplotlib? Set the figure size and adjust the padding between and around the subplots. Using plot () method, plot lines with the labels line1, line2 and line3. Place a legend on the figure using legend () method, with number of labels for ncol value in the argument.

How to place a legend on a figure using Python plot?

Using plot () method, plot lines with the labels line1, line2 and line3. Place a legend on the figure using legend () method, with number of labels for ncol value in the argument.

What is a patch in Matplotlib?

class matplotlib.patches.Patch(edgecolor=None, facecolor=None, color=None, linewidth=None, linestyle=None, antialiased=None, hatch=None, fill=True, capstyle=None, joinstyle=None, **kwargs) [source] # A patch is a 2D artist with a face color and an edge color.

How to increase the size of the legend of a patch?

The easiest way offered by matplotlib in my opinion is to define the properties of the legend using prop size to increase/decrease the legend size. You just need to do the following where you can choose the 'size' as preferred. plt.legend (handles= [patch_1, patch_2], loc='best', prop= {'size': 24})


1 Answers

There is an argument determining the number of columns ncol=.

ax.legend(loc='upper center', handles=legend_handles, fontsize='small', ncol=2)

This should do the trick. Got it from this thread.

like image 126
Ian Avatar answered Oct 19 '22 02:10

Ian