matplotlib传奇顺序水平排序

Dil*_*rix 5 python plot matplotlib legend

有没有办法使绘图图例水平(从左到右)而不是垂直运行,而不指定列数(ncol=...)?

我正在绘制不同数量的行(大约5-15个),而我宁愿不尝试动态计算最佳列数(即,当标签时,不会流失的列数将适合整个数字各种各样).此外,当有多个行时,条目的顺序自上而下,然后是左右; 如果它可以默认为水平,这也将得到缓解.

相关:Matplotlib图例,跨列而不是向下添加项

Olg*_*nik 5

此时似乎matplotlib默认为垂直布局.虽然不理想,但选项是做行数/ 2,作为解决方法:

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)
Run Code Online (Sandbox Code Playgroud)

所以在这里你将获取你正在绘制的行数(via nlines = len(xs))的长度,然后将其转换为多个列,通过ncol = int(math.ceil(nlines/2.))并发送到plt.legend(ncol=ncol)