How to get alternating colours in a dashed line using Matplotlib?

To get alternating colors in a dashed line using Matplotlib, we can overlay two plots with different linestyles and colors. This creates a visually appealing effect where one color shows through the gaps of the dashed pattern.

Steps to Create Alternating Colors

  • Set the figure size and adjust the padding between and around the subplots
  • Get the current axis
  • Create x and y data points using NumPy
  • Plot the same data twice with different linestyles: solid ("-") and dashed ("--")
  • Use different colors for each plot to create the alternating effect
  • Display the figure using show() method

Example

Here's how to create a sine wave with alternating red and yellow colors ?

from matplotlib import pyplot as plt
import numpy as np

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

ax = plt.gca()
x = np.linspace(-10, 10, 100)
y = np.sin(x)

# Plot solid red line first (background)
ax.plot(x, y, '-', color='red', linewidth=5)

# Plot dashed yellow line on top (foreground)
ax.plot(x, y, '--', color='yellow', linewidth=5)

plt.show()

How It Works

The technique works by layering two plots:

  • First plot: A solid red line that serves as the background
  • Second plot: A dashed yellow line overlaid on top
  • The dashed line has gaps, allowing the red background to show through
  • This creates the alternating red-yellow pattern

Alternative Color Combinations

You can experiment with different color combinations for various effects ?

from matplotlib import pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 2, figsize=(10, 8))
x = np.linspace(-10, 10, 100)
y = np.sin(x)

# Blue and white combination
axes[0, 0].plot(x, y, '-', color='blue', linewidth=4)
axes[0, 0].plot(x, y, '--', color='white', linewidth=4)
axes[0, 0].set_title('Blue-White')

# Green and black combination
axes[0, 1].plot(x, y, '-', color='green', linewidth=4)
axes[0, 1].plot(x, y, '--', color='black', linewidth=4)
axes[0, 1].set_title('Green-Black')

# Purple and orange combination
axes[1, 0].plot(x, y, '-', color='purple', linewidth=4)
axes[1, 0].plot(x, y, '--', color='orange', linewidth=4)
axes[1, 0].set_title('Purple-Orange')

# Custom dash pattern
axes[1, 1].plot(x, y, '-', color='navy', linewidth=4)
axes[1, 1].plot(x, y, linestyle=(0, (5, 3)), color='cyan', linewidth=4)
axes[1, 1].set_title('Custom Dash Pattern')

plt.tight_layout()
plt.show()

Customizing Dash Patterns

For more control over the dashing pattern, you can use custom linestyle tuples ?

from matplotlib import pyplot as plt
import numpy as np

plt.figure(figsize=(10, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Custom dash patterns: (offset, (dash_length, gap_length))
patterns = [
    (0, (5, 2)),    # 5-point dash, 2-point gap
    (0, (3, 1, 1, 1)),  # Complex pattern
    (0, (10, 3))    # Long dash, short gap
]

colors = [('red', 'yellow'), ('blue', 'white'), ('green', 'orange')]

for i, (pattern, (color1, color2)) in enumerate(zip(patterns, colors)):
    y_offset = y + i * 0.5  # Offset each line vertically
    
    plt.plot(x, y_offset, '-', color=color1, linewidth=4)
    plt.plot(x, y_offset, linestyle=pattern, color=color2, linewidth=4)

plt.title('Custom Dash Patterns with Alternating Colors')
plt.show()

Conclusion

Creating alternating colors in dashed lines is achieved by overlaying a solid background line with a dashed foreground line. This technique allows for creative visual effects and can enhance the readability of your plots when multiple lines are present.

---
Updated on: 2026-03-25T22:39:46+05:30

753 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements