Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python matplotlib scatter plot : changing colour of data points based on given conditions

I have the following data (four equal-length arrays) :

a = [1, 4, 5, 2, 8, 9, 4, 6, 1, 0, 6]
b = [4, 7, 8, 3, 0, 9, 6, 2, 3, 6, 7]
c = [9, 0, 7, 6, 5, 6, 3, 4, 1, 2, 2]
d = [La, Lb, Av, Ac, Av, By, Lh, By, Lg, Ac, Bt]

I am making a 3d plot of arrays a, b, c :

import pylab
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(a,b,c)

plt.show()

Now, I want to color these scattered points using the array named 'd' such that; if the first letter of corresponding 'i'th element value in d is 'L', then colour the point red, if it starts with 'A' colour it green and if it starts with 'B', colour it blue.

So, first point (1,4,9) should be red, second(4,7,0) red too, third(5,8,7) should be green and so on..

Is it possible to do so? Please help if you have some idea :)

like image 373
Panchi Avatar asked Oct 02 '13 14:10

Panchi


2 Answers

As the documentation for scatter explains, you can pass the c argument:

c : color or sequence of color, optional, default

c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however.

So something like

use_colours = {"L": "red", "A": "green", "B": "blue"}
ax.scatter(a,b,c,c=[use_colours[x[0]] for x in d],s=50)

should produce

coloured points

like image 177
DSM Avatar answered Oct 03 '22 07:10

DSM


http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter

c : color or sequence of color, optional, default

"c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however."

Have you tried this?

like image 26
Garth5689 Avatar answered Oct 03 '22 07:10

Garth5689