I'm plotting a large data set and some regressions in pyplot. The data is colored according to an additional value. I decided to set the number of columns in the legend to 2.
It looks nice for the data points, but for the regressions, I'd like to go back to ncols=1. It is possible to do this within one legend?
(I know, I could declare two legends but I'd like to avoid this...)
Legend in matplotlib is a collection of OffsetBox. In principle, you can change "ncol" within a legend by manually rearranging these offsetboxes. Of course, this needs some knowledge of matplotlib internals and will be difficult for normal users. Not sure what would be the best way to expose this. Here is a simple code that creates two legends and combine them into one.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With