- Object-oriented way of using matplotlib – 1. The Reasons
- Object-oriented way of using matplotlib – 2. MATLAB style versus OO style
- Object-oriented way of using matplotlib – 3. Basics of Object Oriented APIs
- Object-oriented way of using matplotlib – 4. Multiple Subplots
- Object-oriented way of using matplotlib – 5. Customizing Plots, Legend
- Object-oriented way of using matplotlib – 5. Customizing Plots, Ticks
- Object-oriented way of using matplotlib – 5. Customizing Plots, Colorbar
- Object-oriented way of using matplotlib – 6. Artist and Useful Links
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.
- Assign a label for each lines and call the ax.legend()
- Get the handles ( ‘lines’ ) from ax.plot() and assign labels for the handles
- 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]
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.
- 2-tuple ( x, y )
- 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.