Create Dashed Line Contours in Python Matplotlib

Recently, I was working on a data visualization project where I needed to display contour plots with dashed lines. The problem was: I wanted to highlight specific contour levels with different line styles so that my audience could quickly distinguish them.

I knew there had to be a clean way to do this. Over the years, I’ve learned that contour plots are powerful tools, especially when you need to visualize geographical data, weather patterns, or even financial risk levels.

In this tutorial, I’ll show you step by step how to create dashed line contours in Python Matplotlib. I’ll cover multiple methods, explain each in plain English, and provide full code examples that you can run right away.

What is a Contour Plot in Python Matplotlib?

Before we dive into dashed lines, let’s quickly understand what a contour plot is. A contour plot in Python Matplotlib is a way to represent 3D data in 2D. It draws lines that connect points with the same value, much like elevation lines on a topographic map.

This is especially useful when you want to show gradients, density, or intensity of data. By customizing these contour lines with dashed styles, you can make your plots more readable and professional.

Method 1 – Create a Basic Dashed Line Contour in Python Matplotlib

The simplest way to create dashed line contours in Python Matplotlib is by using the contour() function with the linestyles parameter.

Here’s a complete example:

import numpy as np
import matplotlib.pyplot as plt

# Generate sample data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create contour plot with dashed lines
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=10, linestyles='dashed', colors='blue')

# Add contour labels
plt.clabel(contours, inline=True, fontsize=8)

plt.title("Dashed Line Contour in Python Matplotlib")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True, linestyle="--", alpha=0.5)
plt.show()

I executed the above example code and added the screenshot below.

Dashed Line Contours in Python Matplotlib

In this code, I used linestyles=’dashed’ to ensure all contour lines appear as dashed. This method is quick and works well when you want all contour levels to share the same dashed style.

Method 2 – Apply Mixed Dashed and Solid Contours

Sometimes you may want only certain contour levels to be dashed while others remain solid.

Here’s how I handle that in Python Matplotlib:

import numpy as np
import matplotlib.pyplot as plt

# Generate data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y)

# Define levels
levels = np.linspace(-1, 1, 7)

# Create contour plot with mixed styles
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=levels, colors='black')

# Manually set linestyle for each contour
for i, collection in enumerate(contours.collections):
    if i % 2 == 0:  # Dashed for even levels
        collection.set_linestyle('dashed')
    else:           # Solid for odd levels
        collection.set_linestyle('solid')

plt.clabel(contours, inline=True, fontsize=8)
plt.title("Mixed Dashed and Solid Contours in Python Matplotlib")
plt.show()

I executed the above example code and added the screenshot below.

Python Matplotlib Create Dashed Line Contours

In this example, I looped through each contour collection and applied dashed or solid styles alternately.

Method 3 – Customize Dash Patterns in Python Matplotlib

Dashed lines don’t have to look the same. You can customize the dash pattern to make your contours stand out.

Here’s how I do it:

import numpy as np
import matplotlib.pyplot as plt

# Generate data
x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = X**2 - Y**2

# Create contour plot
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=8, colors='red')

# Apply custom dash patterns
for i, collection in enumerate(contours.collections):
    if i % 2 == 0:
        collection.set_linestyle((0, (5, 5)))  # Long dash
    else:
        collection.set_linestyle((0, (1, 3)))  # Dotted style

plt.clabel(contours, inline=True, fontsize=8)
plt.title("Custom Dashed Line Contours in Python Matplotlib")
plt.show()

I executed the above example code and added the screenshot below.

Python Matplotlib Dashed Line Contours

Here, (0, (5, 5)) means a dash of length 5 followed by a gap of 5. You can tweak these numbers to create your own unique dash styles.

Method 4 – Combine Colors and Dashed Contours

In real-world projects, I often need to combine color coding with dashed contours. This makes the visualization more intuitive.

Here’s a practical example:

import numpy as np
import matplotlib.pyplot as plt

# Generate data
x = np.linspace(-4, 4, 150)
y = np.linspace(-4, 4, 150)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X**2 + Y**2) / 4)

# Filled contour background
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, Z, levels=20, cmap='Blues')

# Overlay dashed contour lines
contours = plt.contour(X, Y, Z, levels=10, colors='black', linestyles='dashed')

plt.clabel(contours, inline=True, fontsize=8)
plt.title("Dashed Line Contours with Color Fill in Python Matplotlib")
plt.colorbar(label="Density")
plt.show()

In this code, I first created a filled contour (contourf) and then overlaid dashed contour lines.

Practical Use Cases in the USA

Dashed line contours are not just for academic exercises. I’ve used them in real-world Python projects, such as:

  • Weather Data: Showing rainfall intensity over different regions in Texas.
  • Finance: Highlighting risk levels in stock market heatmaps.
  • Geography: Mapping elevation lines in Colorado with alternating dashed styles.
  • Healthcare: Visualizing patient density across hospitals in New York City.

By combining dashed line contours with color fills, I’ve been able to create visualizations that are both informative and visually appealing.

Tips for Using Dashed Line Contours in Python

Here are some quick tips I’ve learned over the years:

  • Always label your contours with clabel() for clarity.
  • Use contrasting colors when overlaying dashed lines on filled contours.
  • Customize dash patterns to avoid confusion when multiple dashed lines overlap.
  • Keep your plots simple; too many contour levels can make the plot messy.

When I first started using Python Matplotlib, I often overlooked the power of dashed line contours. But once I began applying them in real projects, I realized how much they improved readability and professionalism.

Now, whenever I create contour plots for presentations or client reports, I almost always add dashed lines to highlight critical levels.

You may also read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.