36

对于下面的简单图,有没有办法让 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')

在此处输入图像描述

4

2 回答 2

37

我能想到一种可能的方法。您可以随意订购您的传奇物品。您需要做的就是切换顺序,以便它会给您想要的结果。

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

在此处输入图像描述

于 2012-04-11T07:17:07.313 回答
1

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

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)
于 2018-08-11T22:23:20.067 回答