Search code examples
pythonmatplotlibcolorsscatter-plotscatter3d

How to give only 'n'(say 3) colors randomly to scatterplot points in python?


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()

Solution

  • 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()