9

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

Community
  • 1
  • 1
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119

1 Answers1

5

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)

Olga Botvinnik
  • 1,564
  • 1
  • 14
  • 32
  • Thanks @Olga, but I don't understand how your solution is supposed to work---for example, with `lines=2`, it sets the number of columns to 1. Note that I've already described that `ncol` can be calculated dynamically... that's exactly what I'd like to avoid. – DilithiumMatrix Jan 10 '14 at 23:28
  • Sorry I don't think there's a way to have a horizontal legend without dynamically calculating =\ – Olga Botvinnik Jan 10 '14 at 23:31
  • Yeah, I think that might be the case... It should really be a feature! – DilithiumMatrix Jan 10 '14 at 23:40