view raw
Andrea Ianni ௫ Andrea Ianni ௫ - 6 months ago 93
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)):

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>
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\", line 3258, in scatter
edgecolors=edgecolors, data=data, **kwargs)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\", line 1818, in inner
return func(ax, *args, **kwargs)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\axes\", line 3866, in scatter
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\", line 833, in __init__
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\", 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)

This produces the following graph:

enter image description here