Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I make a single legend for many subplots with matplotlib?

I am plotting the same type of information, but for different countries, with multiple subplots with Matplotlib. That is, I have nine plots on a 3x3 grid, all with the same for lines (of course, different values per line).

However, I have not figured out how to put a single legend (since all nine subplots have the same lines) on the figure just once.

How do I do that?

like image 891
pocketfullofcheese Avatar asked Oct 08 '22 06:10

pocketfullofcheese


People also ask

How do you show legend in all subplots?

Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label. To activate label for each curve, use the legend() method. To display the figure, use the show() method.

How do you set a common title for all subplots?

set_title() method is used to add title to individual subplots while plt. suptitle() method is used to add main title common for all subplots.


1 Answers

There is also a nice function get_legend_handles_labels() you can call on the last axis (if you iterate over them) that would collect everything you need from label= arguments:

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')
like image 339
Ben Usman Avatar answered Oct 23 '22 00:10

Ben Usman