Matplotlib legend, add items across columns instead of down

前端 未结 2 1355
夕颜
夕颜 2020-12-09 07:54

For a simple plot below, is there a way to make matplotlib populate the legend so that it fills the rows left to right, instead of first column then second column?



        
2条回答
  •  既然无缘
    2020-12-09 08:31

    I can think of one possible way. You can order your legend items as you like. All you need to do is to switch the order so that it will give you the result you want.

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

    enter image description here

提交回复
热议问题