pceccon
pceccon

Reputation: 9844

Scatter plot labels in one line - Matplotlib

It's possible to set all labels at once in Matplolib?

For example, I have this piece of code to plot a scatter plot:

cmap = plt.get_cmap('Set1')
colors = [cmap(i) for i in numpy.linspace(0, 1, simulations+1)]

plt.figure(figsize=(7, 7))
plt.scatter(coords[:, 0], coords[:, 1], marker='o', c=colors, s=50, edgecolor='None')
plt.legend(loc='lower left',)

where simulations = 7 and coords is a numpy.array with shape (7, 2).

This gives me a plot like that:

enter image description here

If I change the last line for:

plt.scatter(coords[:, 0], coords[:, 1], marker='o', c=colors, s=50, edgecolor='None', label=range(simulations))
plt.legend(loc='lower left')

I get:

enter image description here

I'm wondering if I'll have to do a loop to do the scatter and set each label of if there is some way to do all at once.

Thank you.

Upvotes: 3

Views: 688

Answers (1)

DanHickstein
DanHickstein

Reputation: 6918

I'm not sure how to do it with a scatter plot. But I'm not sure if there is an advantage to use scatter rather than plot if you want different labels.

How about this?

import numpy as np
import matplotlib.pyplot as plt

n = 10
coords = np.random.random((n,2))

cmap = plt.get_cmap('Set1')

for i, (x, y) in enumerate(coords):
    plt.plot(x, y, 'o', color=cmap(i/float(n)), label='%i'%i, ms=9, mec='none')

plt.axis((-0.5, 1.5, -0.5, 1.5))
plt.legend(loc='lower left', numpoints=1, frameon=False)
plt.show()

enter image description here

Upvotes: 3

Related Questions