How to plot a multi-colored line, like a rainbow using Matplotlib?

Creating multi-colored lines like a rainbow in Matplotlib involves plotting multiple lines with different colors from the VIBGYOR spectrum. This technique is useful for data visualization where you want to distinguish between different datasets or show progression.

Basic Rainbow Line Plot

Here's how to create multiple parallel lines with rainbow colors ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create x data points
x = np.linspace(-1, 1, 10)

# Define rainbow colors (VIBGYOR)
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

# Plot multiple lines with rainbow colors
for i in range(len(colors)):
    plt.plot(x, x + i/20, c=colors[i], lw=7, marker='o')

plt.title("Multi-colored Rainbow Lines")
plt.show()

Single Line with Gradient Colors

To create a single line with gradient rainbow colors, use LineCollection ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# Create data
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

# Create line segments
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

# Create LineCollection with rainbow colormap
lc = LineCollection(segments, cmap='rainbow', linewidths=3)
lc.set_array(x)

# Plot
fig, ax = plt.subplots(figsize=(8, 4))
line = ax.add_collection(lc)
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min()-0.1, y.max()+0.1)
plt.colorbar(line, ax=ax)
plt.title("Single Line with Rainbow Gradient")
plt.show()

Customizing Rainbow Effects

You can customize the rainbow effect with different patterns and styles ?

import numpy as np
import matplotlib.pyplot as plt

# Create curved rainbow lines
t = np.linspace(0, 2*np.pi, 100)
colors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3']

plt.figure(figsize=(8, 6))

for i, color in enumerate(colors):
    radius = 1 + i * 0.3
    x = radius * np.cos(t)
    y = radius * np.sin(t)
    plt.plot(x, y, color=color, linewidth=4, label=f'Ring {i+1}')

plt.axis('equal')
plt.title("Rainbow Circular Lines")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

Comparison of Methods

Method Use Case Complexity
Multiple plt.plot() Parallel lines with different colors Simple
LineCollection Single line with gradient colors Moderate
Custom patterns Complex rainbow shapes Advanced

Conclusion

Use multiple plt.plot() calls for simple rainbow line effects. For gradient colors on a single line, use LineCollection with the rainbow colormap. Custom patterns allow for creative rainbow visualizations.

Updated on: 2026-03-25T19:47:23+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements