简体   繁体   中英

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 (ie 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM