Legend customization

References:

Location string Location code
best 0
upper right 1
upper left 2
lower left 3
lower right 4
right 5
center left 6
center right 7
lower center 8
upper center 9
center 10

In [1]:
import os
setup_script = os.path.join(os.environ['ENV_JUPYTER_SETUPS_DIR'], 'setup_sci_env_basic.py')
%run $setup_script


The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload

In [2]:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

In [3]:
ignore_warnings()

Custom legend markers


In [4]:
red_patch = mpatches.Patch(color='red', label='The red data')

In [5]:
blue_line = mlines.Line2D([], [], color='blue', marker='*',
                          markersize=15, label='Blue stars')

In [6]:
legend_handles = [red_patch, blue_line]

In [7]:
f,a = plt.subplots()
leg = a.legend(handles=legend_handles)
# - Note: you can also call plt.legend(..)


Legend position

Placing above


In [8]:
f,a = plt.subplots()
a.plot([1,2,3], label="test1")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
leg = a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)


Placing to the right


In [9]:
f,a = plt.subplots()
a.plot([1,2,3], label="test1")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
a.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)


Out[9]:
<matplotlib.legend.Legend at 0x7f8318324e48>