创建具有动态列数的matplotlib图例

2024-05-15 03:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matplotlib中创建一个每列最多5个条目的图例。现在,我可以手动设置列数,如下所示:

leg = plt.legend(loc='best', fancybox=None, ncol=2)

如何修改它,使每列最多允许5个条目?在


Tags: 目的nonematplotlib条目plt手动locbest
1条回答
网友
1楼 · 发布于 2024-05-15 03:45:22

没有内置的方法来指定行数而不是列数。但是,您可以使用ax._get_legend_handles()方法获得要添加到图例中的项数。在

例如:

import numpy as np
import matplotlib.pyplot as plt

numlines = np.random.randint(1, 15)
x = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
for i in range(1, numlines + 1):
    ax.plot(x, i * x, label='$y={}x$'.format(i))

numitems = len(list(ax._get_legend_handles()))
nrows = 5
ncols = int(np.ceil(numitems / float(nrows)))

ax.legend(ncol=ncols, loc='best')

plt.show()

enter image description here

相关问题 更多 >

    热门问题