Connecting two points on a 3D scatter plot in Python and Matplotlib

To connect two points on a 3D scatter plot in Python using Matplotlib, we can combine the scatter() method to plot points and plot() method to draw connecting lines between them.

Steps to Connect Points

  • Create a 3D subplot using add_subplot(projection="3d")
  • Define x, y, and z coordinates for the points
  • Plot the points using scatter() method
  • Connect the points using plot() method with the same coordinates
  • Display the plot using show() method

Basic Example

Here's how to connect two points in 3D space ?

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Create figure and 3D subplot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")

# Define coordinates for two points
x = [1, 1.5]
y = [1, 2.4] 
z = [3.4, 1.4]

# Plot the points
ax.scatter(x, y, z, c='red', s=100, label='Points')

# Connect the points with a line
ax.plot(x, y, z, color='black', linewidth=2, label='Connection')

# Add labels and legend
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.legend()

plt.show()

Connecting Multiple Points

You can also connect multiple points in sequence ?

import matplotlib.pyplot as plt

# Create figure and 3D subplot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")

# Define coordinates for multiple points
x = [1, 2, 3, 4]
y = [1, 3, 2, 4]
z = [2, 1, 4, 3]

# Plot the points
ax.scatter(x, y, z, c='blue', s=80, alpha=0.8)

# Connect all points in sequence
ax.plot(x, y, z, color='green', linewidth=2, marker='o')

# Set labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis') 
ax.set_zlabel('Z axis')
ax.set_title('Connected 3D Points')

plt.show()

Customizing the Connection

You can customize the line style, color, and markers ?

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")

# Points to connect
x = [0, 2, 4]
y = [0, 3, 1] 
z = [1, 2, 3]

# Scatter plot with larger points
ax.scatter(x, y, z, c='red', s=150, alpha=0.7, edgecolors='black')

# Connect with dashed line
ax.plot(x, y, z, color='purple', linestyle='--', linewidth=3, 
        marker='s', markersize=8, alpha=0.8)

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('Customized 3D Connection')

plt.show()

Key Parameters

Method Parameter Description
scatter() s Size of points
scatter() c Color of points
plot() linewidth Thickness of connecting line
plot() linestyle Style of line (solid, dashed, etc.)

Conclusion

Use scatter() to plot 3D points and plot() to connect them with lines. Customize colors, sizes, and line styles to create visually appealing 3D visualizations.

Updated on: 2026-03-25T21:24:45+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements