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.
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』.
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]
ⅲ. 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.
- 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.