Search code examples
python-3.xmatplotlibscatter-plot

Connect points to center in matplotlib scatter plot


I am scattering points in a 3-dimension frame; do you how could it be possible to join each of these points by a segment (or vector) to the center (0,0,0) of the frame ? Here is the code used:

from numpy import random
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d 

N = 10
coords = random.normal(loc = 0, scale = 1, size = (N, 3))

x = coords[:, 0]
y = coords[:, 1]
z = coords[:, 2]

fig = plt.figure(figsize=(12,12))
ax = plt.axes(projection ="3d") 

ax.scatter3D(x, y, z, color = "green", s = 300)

And here is the plot obtained:

enter image description here

What I would like to get is:

enter image description here


Solution

  • One option is to iterate over each of your points, and use plot3D to draw a line from (0, 0, 0) to that point.

    from numpy import random
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from mpl_toolkits import mplot3d 
    
    N = 10
    coords = random.normal(loc = 0, scale = 1, size = (N, 3))
    
    x = coords[:, 0]
    y = coords[:, 1]
    z = coords[:, 2]
    
    fig = plt.figure(figsize=(12,12))
    ax = plt.axes(projection ="3d") 
    
    for xx, yy, zz in zip(x, y, z):
        ax.plot3D([0, xx], [0, yy], [0, zz], color = "blue")
    
    ax.scatter3D(x, y, z, color = "green", s = 300)
    
    plt.show()
    

    enter image description here