Skill - Matplotlib legend at the bottom of the plot
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Matplotlib plotting library
- Styling Matplotlib plots
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Matplotlib is a plotting library tn the scipy ecosystem of libraries.
Please make sure that you covered the post on basics
In order to place the legend at the bottom using ax.legend
function, we can use the following options
bbox_to_anchor
- location of the legend anchor w.r.t the plot bounding box. Anchor location is specified as (x,y)loc
- Location of the legend anchor w.r.t legend boxncol
- Max number of columns in the legend boxborderaxespad
- padding between axes and legend border in terms of font-size
import matplotlib.pyplot as plt
import random
fig, ax = plt.subplots()
numLines = 5
for k in range(numLines):
vals = [random.randint(0, 10) for x in range(4)]
la, = ax.plot([1, 2, 3, 4], vals)
la.set_label("Another line {0}".format(k+1))
ax.legend(bbox_to_anchor=(0, -.1), loc='upper left',
ncol=3, borderaxespad=0)
ax.set_title("Figure Title")
plt.show()
Video
You can the video on this post here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/
References
- Awesome blog post on legend placement - https://jdhao.github.io/2018/01/23/matplotlib-legend-outside-of-axes/
- Official legend function documentation - https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html#matplotlib.axes.Axes.legend
Comments
Post a Comment