2012-04-11 29 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

相關問題