Yotam Yotam - 1 year ago 278
Python Question

Setting different color for each series in scatter plot on matplotlib

Suppose I have three data sets:

X = [1,2,3,4]
Y1 = [4,8,12,16]
Y2 = [1,4,9,16]

I can scatter plot this:

from matplotlib import pyplot as plt

How can I do this with 10 sets?

I searched for this and could find any reference to what I'm asking.

Edit: clearing (hopefully) my question

If I call scatter multiple times, I can only set the same color on each scatter. Also, I know I can set a color array manually but I'm sure there is a better way to do this.
My question is then, "How can I automatically scatter plot my several data set, each with different colors.

If that helps, I can easily assign a unique number to each data set.

Answer Source

I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:

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

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
    plt.scatter(x, y, color=c)

or make your own colour cycler using itertools.cycle and specifying the colours you want to loop over, using next to get the one you want. For example (I'm too lazy to type out ten colours):

colors = itertools.cycle(["r", "b", "g"])
for y in ys:
    plt.scatter(x, y, color=next(colors))

Come to think of it, maybe it's cleaner not to use zip with the first one too:

colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
    plt.scatter(x, y, color=next(colors))

[PS: I really hate that I have to drop the 'u' when working with matplotlib..]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download