Line colour of a 3D parametric curve in Python's Matplotlib.pyplot

To create a 3D parametric curve with customized line colors in Matplotlib, we need to generate parametric equations and apply color mapping based on parameter values. This technique is useful for visualizing how curves change through parameter space.

Steps to Create a Colored 3D Parametric Curve

  • Set the figure size and adjust the padding between and around the subplots.

  • Create a new figure or activate an existing figure using figure() method.

  • Add an axis as a subplot arrangement with 3D projection.

  • To make a parametric curve, initialize theta, z, r, x and y variables.

  • Plot x, y and z data points using scatter() method with color mapping.

  • Set the title of the plot.

  • To display the figure, use show() method.

Example

Here's how to create a 3D parametric curve with colors mapped to the x-coordinate values ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

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

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.scatter(x, y, z, c=x, cmap="copper")
ax.set_title("Parametric Curve")
plt.show()

Using plot() Instead of scatter()

For a continuous line representation, you can use plot() with color segmentation ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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

theta = np.linspace(0, 6 * np.pi, 200)
x = np.cos(theta)
y = np.sin(theta)
z = theta / (2 * np.pi)

# Create color array based on z values
colors = plt.cm.viridis(z / z.max())

# Plot line segments with different colors
for i in range(len(theta) - 1):
    ax.plot([x[i], x[i+1]], [y[i], y[i+1]], [z[i], z[i+1]], 
            color=colors[i], linewidth=2)

ax.set_title("3D Helix with Color Gradient")
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

Color Mapping Options

Parameter Description Example
c=x Color by x-coordinate Horizontal gradient
c=theta Color by parameter value Sequential progression
c=z Color by z-coordinate Vertical gradient

Common Colormaps

Popular colormap options for 3D parametric curves include viridis, plasma, copper, and jet for different visual effects.

Conclusion

Use scatter() with the c parameter for point-based color mapping in 3D parametric curves. For continuous lines, segment the curve and apply colors individually to create smooth gradients along the parameter space.

Updated on: 2026-03-25T21:48:37+05:30

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements