pyplot:更改图例中的ncols

Tyr*_*rax 3 matplotlib multiple-columns legend-properties

我正在绘制一个大型数据集和pyplot中的一些回归.数据根据附加值着色.我决定将图例中的列数设置为2.

它看起来很适合数据点,但对于回归,我想回到ncols = 1.在一个传奇中可以做到这一点吗?

(我知道,我可以宣布两个传说,但我想避免这个......)

小智 5

matplotlib中的图例是OffsetBox的集合.原则上,您可以通过手动重新排列这些偏移框来更改图例中的"ncol".当然,这需要matplotlib内部的一些知识,对普通用户来说很难.不确定揭露这个的最佳方式是什么.这是一个简单的代码,它创建两个图例并将它们合并为一个.

import matplotlib.pyplot as plt
import matplotlib.legend as mlegend

ax = plt.subplot(111)
l1, = ax.plot([1,2,3])

leg1 = ax.legend([l1], ["long lable"], ncol=1)

leg2 = mlegend.Legend(ax, [l1, l1, l1, l1], tuple("1234"), ncol=2)

leg1._legend_box._children.append(leg2._legend_box._children[1])
leg1._legend_box.align="left" # the default layout is 'center'

plt.show()
Run Code Online (Sandbox Code Playgroud)