Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyplot: change ncols within a legend

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

like image 416
Tyrax Avatar asked Mar 23 '23 00:03

Tyrax


1 Answers

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()
like image 80
Jae-Joon Lee Avatar answered Apr 07 '23 09:04

Jae-Joon Lee