Skip to content
Advertisement

Connect 3D points in matplotlib scatter

I have the following code, that generates a 3D scatter plot:

df_subset = pd.DataFrame(a_dict)

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import ListedColormap
cmap = ListedColormap(sns.color_palette("husl", 256).as_hex())

fig = plt.figure(figsize=(16,15))
ax = Axes3D(fig)
fig.add_axes(ax)
sc = ax.scatter(tsne[:,0], tsne[:,1], tsne[:,2], s=40, c=tsne[:,0], marker='o', cmap=cmap, alpha=1)
ax.set_xlabel('First Dimention')
ax.set_ylabel('Second Dimention')
ax.set_zlabel('Third Dimention')

What I’m trying to do is connect those 2 points using a directional arrow.

What I’ve got

What I want: What i want

Tried ax.annotation but it doesn’t work. Any suggestions? Preferencially, a for loop to annotate N points, considering the (x1, y1, z1) and (x2, y2, z2) coordinates.

Advertisement

Answer

This is a possible solution, p1 and p2 are just some points for testing purpose:

p1 = np.arange(4)
p2 = np.arange(4) * 2

fig = plt.figure()
ax = plt.axes(projection='3d')

sc1 = ax.scatter(p1[0], p1[1], p1[2],c=p1[3], marker='o', cmap='jet')
sc2 = ax.scatter(p2[0], p2[1], p2[2],c=p2[3], marker='o', cmap='jet')

ax.set_xlabel('First Dimension')
ax.set_ylabel('Second Dimension')
ax.set_zlabel('Third Dimension')

ax.quiver3D(p1[0], p1[1], p1[2], (p2[0]-p1[0]), (p2[1]-p1[1]), (p2[2]-p1[2]), length=1, arrow_length_ratio=0.1)

Output:

enter image description here

basically ax.quiver3D has following parameter in the parenthesis:

(x, y, z, dx, dy, dz)

x, y, z is the initial position and dx, dy, dz is the vector direction.

As for the loop, I think you will manage to adapt the code yourself, will you?

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement