Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib legend order horizontally first

Is there a way to make a plot legend run horizontally (left to right) instead of vertically, without specifying the number of columns (ncol=...)?

I'm plotting a varying number of lines (roughly 5-15), and I'd rather not try to calculate the optimal number of columns dynamically (i.e. the number of columns that will fit across the figure without running off, when the labels are varying). Also, when there is more than a single row, the ordering of entries goes top-down, then left-right; if it could default to horizontal, this would also be alleviated.

Related: Matplotlib legend, add items across columns instead of down

like image 462
DilithiumMatrix Avatar asked Jan 10 '14 08:01

DilithiumMatrix


1 Answers

It seems at this time that matplotlib defaults to a vertical layout. Though not ideal, an option is to do the number of lines/2, as a workaround:

import math
import numpy as np

npoints = 1000


xs = [np.random.randn(npoints) for i in 10]
ys = [np.random.randn(npoints) for i in 10]

for x, y in zip(xs, ys):
    ax.scatter(x, y)    

nlines = len(xs)
ncol = int(math.ceil(nlines/2.))
plt.legend(ncol=ncol)

So here you would take the length of the number of lines you're plotting (via nlines = len(xs)) and then transform that into a number of columns, via ncol = int(math.ceil(nlines/2.)) and send that to plt.legend(ncol=ncol)

like image 88
Olga Botvinnik Avatar answered Oct 01 '22 19:10

Olga Botvinnik