Object-oriented way of using matplotlib – 5. Customizing Plots, Legend

This entry is part 5 of 8 in the series OO matplotlib





I would like to post a series of articles about object-oriented way of using matplotlib. That explains why we should use that way and how to code like that. The main references are come from the official matplotlib website, “matplotlib.org” and  the book, 『Python Data Science Handbook: Essential Tools for Working with Data, Jake VanderPlas, O’REILLY, 2017』.

In the previous posts, we’ve tasted some differences between MATLAB styles and OO styles. We could learn how to add subplots in different ways. In this post, you can learn how to customize the various stuffs of a plot such as legend, tick and colorbar.

5. Customizing Plots

a. Customizing Legend

ⅰ. Legend for multi lines

There are different ways to add a legend for multiple lines in a subplot.

  1. Assign a label for each lines and call the ax.legend()
  2. Get the handles ( ‘lines’ ) from ax.plot() and assign labels for the handles
  3. Get the handles ( ‘lines’ ) from ax.plot() and assign labels when calling ax.legend()

We are going to see the example code below.
The full source code is available from here. [Link]

ⅱ. Customizing Legend

I will compare the MATLAB style codes and OO style codes of customizing legend here. The OO style codes use ax.legend() instead of using plt.legend(). And an axes object can make a legend with handles and its labels so that you should get the handles if you haven’t designated the labels inside the plot() method.

The full source code is here. [Link]

ⅲ. bbox_to_anchor

When you customize legend, you can adjust the location of it by specifying location and bbox_to_anchor. A location is a relative position to the bbox_to_anchor which is a bounding box region to anchor the legend. When you specify the bbox_to_anchor, there are two ways.

  1. 2-tuple ( x, y )
  2. 4-tuple ( x, y, width, height )

Don’t misunderstand that bbox is the same as legend box. You can understand overall concept from the examples. I found this link is really helpful. [Link]

And Let’s look at how to code that below.

Series Navigation<< Object-oriented way of using matplotlib – 4. Multiple SubplotsObject-oriented way of using matplotlib – 5. Customizing Plots, Ticks >>

Leave a Comment