2024-05-15 03:45:22 发布
网友
我想在matplotlib中创建一个每列最多5个条目的图例。现在,我可以手动设置列数,如下所示:
leg = plt.legend(loc='best', fancybox=None, ncol=2)
如何修改它,使每列最多允许5个条目?在
没有内置的方法来指定行数而不是列数。但是,您可以使用ax._get_legend_handles()方法获得要添加到图例中的项数。在
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()
没有内置的方法来指定行数而不是列数。但是,您可以使用
ax._get_legend_handles()
方法获得要添加到图例中的项数。在例如:
相关问题 更多 >
编程相关推荐