Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple colors in matplotlib plot

I have a numpy array of 2D data points (x,y), which are classified into three categories (0,1,2).

a = array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
           [ 9, 8, 7, 6, 5, 4, 3, 2 ]])

class = array([0, 2, 1, 1, 1, 2, 0, 0])

My question is if I can plot these points with multiple colors. I would like to do something like this:

colors = list()
for i in class:
    if i == 0:
        colors.append('r')
    elif i == 1:
        colors.append('g')
    else:
        colors.append('b')

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

pp.plot(a[0], a[1], color = colors)
like image 874
dpindk Avatar asked Mar 28 '13 09:03

dpindk


People also ask

Is it possible to create a Coloured scatterplot using matplotlib?

Use matplotlib. pyplot. scatter() to make a colored scatter plot. Using lists of corresponding x and y coordinates and a list colors , create a list color_indices that assigns each coordinate the index of a color from colors .


1 Answers

I assume you want to plot distinct points. In that case, if you define a numpy array:

colormap = np.array(['r', 'g', 'b'])

then you can generate the array of colors with colormap[categories]:

In [18]: colormap[categories]
Out[18]: 
array(['r', 'b', 'g', 'g', 'g', 'b', 'r', 'r'], 
      dtype='|S1')

import matplotlib.pyplot as plt
import numpy as np

a = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
              [ 9, 8, 7, 6, 5, 4, 3, 2 ]])

categories = np.array([0, 2, 1, 1, 1, 2, 0, 0])

colormap = np.array(['r', 'g', 'b'])

plt.scatter(a[0], a[1], s=50, c=colormap[categories])
plt.show()

yields

enter image description here

like image 174
unutbu Avatar answered Sep 23 '22 13:09

unutbu