Matplotlib legend at the bottom of the plot

matplotlib_bottom_legend

Skill - Matplotlib legend at the bottom of the plot

Table of Contents

Skills Required

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 box
  • ncol - Max number of columns in the legend box
  • borderaxespad - 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()

matplotlib_bottom_legend_demo

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


Table of Contents

Comments