0

I have made a scatter plot in the following way:

f, ax1 = plt.subplots(3,2)
cmap = matplotlib.cm.get_cmap('coolwarm')
ax1[0,1].scatter(data[:,0], data[:,1], c=y, s=20, marker='o', alpha=.5, cmap=cmap)

data holds the data and y holds the labels (1,2,3). Now I would like to add a legend.

ax1[0,1].legend(('label1', 'label2', 'label3'),
           scatterpoints=1,
           loc='lower left',
           fontsize=10)

This does not work, it only prints label1. How can this be done otherwise?

1 Answer 1

1

The idea is to divide data set on separate data sets which are represented by the same color. After that the legend displayed properly.

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

data = np.zeros(shape=(10,2))
data[:,0] = np.linspace(0,1,10)
data[:,1] = np.linspace(0,1,10)

y = ['red', 'green', 'blue']
f, ax1 = plt.subplots(3,2)
cmap = matplotlib.cm.get_cmap('coolwarm')
ny = len(y)
for i, itm in enumerate(y):
    datac = data[i::ny,:]
    ax1[0,1].scatter(datac[:,0], datac[:,1], c=itm, 
                     s=20, marker='o', alpha=.5, cmap=cmap)

ax1[0,1].legend(['label1', 'label2', 'label3'],
           scatterpoints=1,
           loc='lower left',
           fontsize=10)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.