plotting
data visualization
matplotlib
graph customization
line styling

How to get different colored lines for different plots in a single figure

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

When several series share one figure, color is usually the first thing that helps the reader separate them. Matplotlib already cycles colors automatically, but explicit color control is better when you need consistency, accessibility, or a chart that will be reproduced in reports and notebooks.

Let Matplotlib Use Its Default Cycle

For quick exploratory work, calling plot repeatedly on the same axes is enough. Matplotlib assigns a different color to each line from its default cycle.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4x = np.linspace(0, 2 * np.pi, 200)
5
6plt.plot(x, np.sin(x), label="sin")
7plt.plot(x, np.cos(x), label="cos")
8plt.plot(x, np.sin(2 * x), label="sin(2x)")
9
10plt.legend()
11plt.title("Default Matplotlib Color Cycle")
12plt.show()

This is fine for ad hoc plots, but the colors may shift if you change plotting order or insert another series later.

Assign Explicit Colors for Stable Output

If the same series should always have the same color, set the color yourself.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4x = np.linspace(0, 10, 300)
5
6plt.plot(x, np.log1p(x), color="#1b9e77", linewidth=2, label="log1p")
7plt.plot(x, np.sqrt(x), color="#d95f02", linewidth=2, label="sqrt")
8plt.plot(x, x / 10, color="#7570b3", linewidth=2, label="linear")
9
10plt.legend()
11plt.title("Explicit Color Mapping")
12plt.show()

Hex colors are often the easiest format when you need to match a design system or reuse chart colors across several files.

Generate Many Distinct Colors Programmatically

Manual color assignment becomes tedious when you have many lines. In that case, sample from a qualitative colormap.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4x = np.linspace(0, 8, 250)
5num_lines = 10
6cmap = plt.cm.get_cmap("tab10", num_lines)
7
8fig, ax = plt.subplots(figsize=(9, 5))
9for i in range(num_lines):
10    y = np.sin(x + i * 0.3)
11    ax.plot(x, y, color=cmap(i), label=f"series_{i}")
12
13ax.legend(ncol=2)
14ax.set_title("Programmatic Colors")
15plt.show()

For categorical lines, colormaps such as tab10, tab20, or Set2 are usually a better fit than continuous ramps like viridis.

Keep Colors Consistent Across Figures

If the same labels appear across several charts, build a palette dictionary and reuse it everywhere.

python
1palette = {
2    "baseline": "#4e79a7",
3    "experiment_a": "#f28e2b",
4    "experiment_b": "#59a14f",
5}
6
7# Example:
8# ax.plot(x, y_baseline, color=palette["baseline"], label="baseline")

This prevents a common reporting problem where the same series is blue in one chart and orange in the next.

Combine Color With Other Visual Cues

Color alone is not always enough. Some readers are color-impaired, some charts are printed in grayscale, and some palettes simply do not separate nearby hues well. Add line styles or markers when clarity matters.

python
1styles = ["-", "--", "-.", ":"]
2colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"]
3
4for i in range(4):
5    plt.plot(
6        x,
7        np.sin(x + i * 0.4),
8        linestyle=styles[i],
9        color=colors[i],
10        marker="o",
11        markevery=30,
12        label=f"line_{i}",
13    )
14
15plt.legend()
16plt.title("Color Plus Style")
17plt.show()

That makes the figure easier to interpret even when color information is weak.

Seaborn and Plotly Follow the Same Pattern

The exact API differs, but the idea is the same in other libraries. In Seaborn, map categories to a palette with hue. In Plotly, set per-trace line colors explicitly. Deterministic color mapping by series identity is the underlying concept regardless of the library.

python
1import pandas as pd
2import seaborn as sns
3
4df = pd.DataFrame({
5    "x": np.tile(x, 2),
6    "y": np.concatenate([np.sin(x), np.cos(x)]),
7    "series": ["sin"] * len(x) + ["cos"] * len(x),
8})
9
10sns.lineplot(data=df, x="x", y="y", hue="series", palette={"sin": "#4e79a7", "cos": "#f28e2b"})
11plt.show()

Common Pitfalls

The most common mistake is relying on the default color order when plot order can change. That makes charts inconsistent across edits.

Another issue is using too many visually similar colors on one axes. Once the hues become hard to distinguish, add line styles, markers, or reduce the number of simultaneously displayed series.

Developers also often pick continuous colormaps for category data. That makes the colors imply an ordering that may not exist.

Finally, if the same series appears in multiple figures, keep the mapping fixed. Reassigning colors from chart to chart increases reader error.

Summary

  • Matplotlib already gives different colors to successive plot calls on the same axes.
  • Use explicit colors when you need stable, repeatable chart output.
  • Sample from a qualitative colormap when plotting many categories.
  • Combine color with markers or line style for accessibility and clarity.
  • Reuse one palette mapping across related figures so the same series always looks the same.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design