Matplotlib图例,跨列而不是向下添加项目 [英] Matplotlib legend, add items across columns instead of down

查看:123
本文介绍了Matplotlib图例,跨列而不是向下添加项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的简单图解,是否有一种方法可以使matplotlib填充图例,以使其填充从左到右的行,而不是第一列然后第二列?

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?

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

推荐答案

我可以想到一种可能的方法.您可以订购图例项为你喜欢.您所需要做的就是切换顺序,以便为您提供所需的结果.

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

这篇关于Matplotlib图例,跨列而不是向下添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆