【问题标题】:Matplotlib legend, add items across columns instead of downMatplotlib 图例,跨列而不是向下添加项目
【发布时间】:2012-04-11 06:43:30
【问题描述】:

对于下面的简单绘图,有没有办法让 matplotlib 填充图例,以便它从左到右填充行,而不是第一列然后第二列?

>>> from pylab import *
>>> x = arange(-2*pi, 2*pi, 0.1)
>>> plot(x, sin(x), label='Sine')
>>> plot(x, cos(x), label='Cosine')
>>> plot(x, arctan(x), label='Inverse tan')
>>> legend(loc=9,ncol=2)
>>> grid('on')

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    我能想到一种可能的方法。你可以order your legend items 随意。您需要做的就是切换顺序,这样它就会给您想要的结果。

    import matplotlib.pyplot as plt
    import numpy as np
    import itertools
    
    def flip(items, ncol):
        return itertools.chain(*[items[i::ncol] for i in range(ncol)])
    
    x = np.arange(-2*np.pi, 2*np.pi, 0.1)
    ax = plt.subplot(111)
    ax.plot(x, np.sin(x), label='Sine')
    ax.plot(x, np.cos(x), label='Cosine')
    ax.plot(x, np.arctan(x), label='Inverse tan')
    
    handles, labels = ax.get_legend_handles_labels()
    plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=2)
    
    plt.grid('on')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      默认情况下,图例将在添加新行之前填充所有分配的列。因此,您可以将句柄和标签重新排序以利用这一点:

      handles, labels = ax1.get_legend_handles_labels()
      handles = np.concatenate((handles[::2],handles[1::2]),axis=0)
      labels = np.concatenate((labels[::2],labels[1::2]),axis=0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        • 2020-11-30
        • 2021-01-28
        • 2020-12-13
        • 2014-08-08
        相关资源
        最近更新 更多