0

Generated random numbers x,y,z, then put them in scatter 3d plot but am unable to plot the points, randomly with 3 specific colors (say red,black,yellow).

In documentation of matplotlib.pyplot.scatter, I am unable to understand the other 3 ways of specifying colors except the 1st one.

Code:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',color='b')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
Rex5
  • 771
  • 9
  • 23

1 Answers1

1

If you just want to randomly assign color to each point from set of n colors, you can do it like this:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)
n=3
colors = np.random.randint(n, size=x.shape[0])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',c=colors)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
pmarcol
  • 453
  • 2
  • 9
  • can you please elaborate the 3 points of documentation :The marker color. Possible values: A single color format string. A sequence of color specifications of length n. A sequence of n numbers to be mapped to colors using cmap and norm. A 2-D array in which the rows are RGB or RGBA. – Rex5 May 29 '19 at 12:27
  • 1
    and if you want to specify the color palette, replace the `colors` array definition with: `colors = np.random.choice(['red','black','yellow'], size=x.shape[0])` – pmarcol May 29 '19 at 12:27
  • thanks that works ! can't accept before 8 minutes ! – Rex5 May 29 '19 at 12:29
  • 1
    as to your question on documentation of c argument: 1st option is just one color, e.g. 'red' - all points will be red. 2nd point - list of colors, e.g. ['red', 'blue', 'black', 'red', ...] - one color per point. Number of the data points must match the length of the c array (this approach is used in the command given in the comment). 3rd point - you pass numbers, that are mapped to scale (from 0 to 1, I believe) - `matplotlib` has number of colormaps that just map number to color (e.g. from black to white, from blue to red through purple etc.). 4th point - you give RGB values, 3 per each point – pmarcol May 29 '19 at 12:36