How to plot a single line in Matplotlib that continuously changes color?

To plot a single line that continuously changes color in Matplotlib, you can segment the line into small parts and assign different colors to each segment. This creates a smooth color transition effect along the line.

Steps

Here's how to create a color-changing line ?

  • Set the figure size and adjust the padding between subplots
  • Create data points using NumPy (we'll use a sine wave)
  • Create a figure and subplot
  • Iterate through the data in small segments
  • Plot each segment with a different random color
  • Display the figure using show() method

Example

import matplotlib.pyplot as plt
import numpy as np
import random

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

x = np.linspace(1, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()

for i in range(0, 100, 5):
    r = random.random()
    b = random.random()
    g = random.random()
    color = (r, g, b)
    ax.plot(x[i:i+5+1], y[i:i+5+1], c=color, lw=7)

plt.show()

Using a Color Map for Smooth Transitions

For more professional-looking color transitions, you can use matplotlib's built-in color maps ?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(8, 4))

# Create color map
colors = plt.cm.rainbow(np.linspace(0, 1, 20))

# Plot segments with different colors
for i in range(0, 95, 5):
    color_idx = i // 5
    ax.plot(x[i:i+6], y[i:i+6], c=colors[color_idx], linewidth=5)

plt.title("Single Line with Continuous Color Change")
plt.show()

How It Works

The technique works by:

  • Segmentation: Breaking the line into overlapping segments
  • Color assignment: Each segment gets a different color
  • Overlap: Small overlaps between segments create smooth transitions
  • Line width: Thicker lines make color changes more visible

Comparison of Methods

Method Color Control Visual Quality Best For
Random colors Low Vibrant but chaotic Artistic effects
Color maps High Smooth gradients Scientific visualization

Conclusion

Use overlapping line segments with different colors to create continuously changing color effects. Color maps provide smoother transitions than random colors for professional visualizations.

Updated on: 2026-03-25T22:10:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements