Ayyappan Subramaniyan
Ayyappan Subramaniyan

Reputation: 77

How to create out side legend in scatter plot(Matplotlib)

I am using following code to generate scatter plot.

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='best',
           ncol=3,
           fontsize=8)
plt.savefig('foo111.png')

I would like to display the legend, out side of the plot. Please help me to achieve this.

Note: Currently i am using matplotlib(1.4.3) and Python 2.7

Upvotes: 0

Views: 124

Answers (1)

user3590169
user3590169

Reputation: 396

Try doing something along these lines.

ax = plt.subplot(111)

lo = ax.scatter(random(10), random(10), marker='x', color=colors[0])
ll = ax.scatter(random(10), random(10), marker='o', color=colors[0])
...

plt.legend((lo, ll, l, a, h, hh, ho),
       ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
       scatterpoints=1,
       loc='center left',
       bbox_to_anchor=(1, 0.5),
       ncol=3,
       fontsize=8)

It may be worth having a look at the matplotlib legend docs to see how to use this more fully.

Upvotes: 1

Related Questions