2012-04-11 26 views
24

对于下面的简单图,是否有一种方法可以使matplotlib填充图例,以便从左到右填充行,而不是第一列和第二列?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') 

enter image description here

回答

20

我能想到的一种可能的方式。只要你喜欢,你可以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() 

enter image description here

相关问题