Andrea Ianni ௫ - 1 year ago 249
Python Question

pylab: plotting points with colors

I'm trying to plot points in the two-dimensional space, inserting labels and where the color of every point is set (not dependent on the label).
The first try, not considering the labels is:

``````import pylab
x = [-0.01611772,  1.51755901, -0.64869352, -1.80850313, -0.11505037]
y = [ 0.04845168, -0.45576903,  0.62703651, -0.24415787, -0.41307092]
colors = ['b', 'g', 'r', 'b', 'r']

for k in range(len(x)):
pylab.scatter(x[k],y[k],colors[k])
``````

It returns an error that doesn't fit with the operations necessary to perform a plot:

``````Traceback (most recent call last):
File "<pyshell#1>", line 12, in <module>
pylab.scatter(x[k],y[k],colors[k])
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 3258, in scatter
edgecolors=edgecolors, data=data, **kwargs)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\__init__.py", line 1818, in inner
return func(ax, *args, **kwargs)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\axes\_axes.py", line 3866, in scatter
alpha=alpha
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\collections.py", line 833, in __init__
self.set_sizes(sizes)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\collections.py", line 806, in set_sizes
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
``````

Anyone having ideas?

There is no need to use a for loop here. Simply pass your list of colours into the `pylab.scatter` function:

``````import pylab

x = [-0.01611772,  1.51755901, -0.64869352, -1.80850313, -0.11505037]
y = [ 0.04845168, -0.45576903,  0.62703651, -0.24415787, -0.41307092]

colors = ['b', 'g', 'r', 'b', 'r']

pylab.scatter(x, y, c=colors)

pylab.show()
``````

This produces the following graph:

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