【问题标题】:matplotlib legend order horizontally firstmatplotlib 图例先水平排列
【发布时间】:2014-01-29 02:36:11
【问题描述】:

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

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

相关:Matplotlib legend, add items across columns instead of down

【问题讨论】:

    标签: python matplotlib plot legend


    【解决方案1】:

    此时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)
    

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

    【讨论】:

    • 谢谢@Olga,但我不明白您的解决方案应该如何工作——例如,使用lines=2,它将列数设置为1。请注意,我已经已经描述了ncol 可以动态计算……这正是我想要避免的。
    • 对不起,我认为没有办法在不动态计算的情况下获得水平图例 =\
    • 是的,我认为可能是这种情况......它应该真的是一个功能!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2015-03-06
    • 2016-07-14
    相关资源
    最近更新 更多