Search code examples
pythonmatplotlibplotpoint-cloudscentroid

Add a point to a scatter plot in python


I have a point cloud and to show it I use the matpyplot library. Then I want to add to this figure one point which is the centroid of that cloud. Here my code

point_list, centroid_list = points(dataset[:, :7])
# take one point cloud 
points = np.array(point_list[0])
# take the centroid of that point cloud
centroid = np.array(centroid_list[0])
f = plt.figure(figsize=(15, 8))
ax = f.add_subplot(111, projection='3d')
ax.scatter(*np.transpose(points[:, [0, 1, 2]]), s=1, c='#FF0000', cmap='gray')
ax.plot(centroid, 'or') # this line doesn't work
plt.show()

The line to draw the point cloud is my problem, I don't know how to add a point. I've tried with some solutions in other thread but they don't work. I would like to draw the centroid in another color and maybe bigger, example using the notation for the scatter plot s=5, c='#00FF00'.


Solution

  • Following working code should give you some insight. In your code, somehow, dimensions/shape of centroid are not coherent. You might want to adapt the line accordingly.

    from matplotlib import pyplot as plt
    from mpl_toolkits.mplot3d import axes3d
    import numpy as np
    
    points = np.random.normal(size=(20,3))
    # take the centroid of that point cloud
    centroid = np.asarray([0.,0.,0.])
    f = plt.figure(figsize=(15, 8))
    ax = f.add_subplot(111, projection='3d')
    ax.scatter(*np.transpose(points[:, [0, 1, 2]]), s=1, c='#FF0000', cmap='gray')
    ax.plot([centroid[0]],[centroid[1]],[centroid[2]],'or') # this line doesn't work
    plt.show()