How can I get the (x,y) values of a line that is plotted by a contour plot (Matplotlib)?

To get the (x, y) values of a line plotted by a contour plot in Matplotlib, you need to access the contour collections and extract the path vertices. This is useful for analyzing specific contour lines or extracting data for further processing.

Steps to Extract Contour Line Coordinates

  • Create a contour plot using contour() method
  • Access the contour collections from the returned object
  • Get the paths from each collection
  • Extract vertices (x, y coordinates) from each path

Example

Here's how to extract the (x, y) coordinates from contour lines ?

import matplotlib.pyplot as plt
import numpy as np

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

# Create sample data
m = [[3, 2, 1, 0], [2, 4, 1, 0], [2, 4, 1, 3], [4, 3, 1, 3]]

# Create contour plot
cs = plt.contour([3, 4, 2, 1], [5, 1, 2, 3], m)

# Get paths from the first contour level
paths = cs.collections[0].get_paths()

# Extract and print vertices
for i, path in enumerate(paths):
    vertices = path.vertices
    print(f"Contour line {i + 1}:")
    print(f"X coordinates: {vertices[:, 0]}")
    print(f"Y coordinates: {vertices[:, 1]}")
    print()

plt.show()
Contour line 1:
X coordinates: [3.5 3.  3. ]
Y coordinates: [5.  4.5 3. ]

Contour line 2:
X coordinates: [1.5 2.  3.5]
Y coordinates: [3.  3.  1.5]

Accessing All Contour Levels

To extract coordinates from all contour levels, iterate through all collections ?

import matplotlib.pyplot as plt
import numpy as np

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

# Create contour plot with multiple levels
cs = plt.contour(X, Y, Z, levels=5)

# Extract coordinates from all contour levels
for level_idx, collection in enumerate(cs.collections):
    level_value = cs.levels[level_idx]
    print(f"Contour level {level_value:.2f}:")
    
    paths = collection.get_paths()
    for path_idx, path in enumerate(paths):
        vertices = path.vertices
        print(f"  Path {path_idx + 1}: {len(vertices)} points")
        # Print first few points
        print(f"  First 3 points: {vertices[:3]}")
    print()

plt.title("Contour Plot with Multiple Levels")
plt.show()

Practical Use Case

Here's how to store contour coordinates for further analysis ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(-1, 1, 50)
y = np.linspace(-1, 1, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create contour plot
cs = plt.contour(X, Y, Z, levels=[0])

# Store contour coordinates in a list
contour_coords = []
for collection in cs.collections:
    for path in collection.get_paths():
        vertices = path.vertices
        contour_coords.append(vertices)

# Display results
print(f"Found {len(contour_coords)} contour lines")
print(f"First contour line has {len(contour_coords[0])} points")
print(f"Sample coordinates: {contour_coords[0][:3]}")

plt.title("Sin Function Contour at Level 0")
plt.show()

Conclusion

Use cs.collections[i].get_paths() to access contour line coordinates. Each path contains vertices as (x, y) coordinate pairs. This technique is essential for extracting numerical data from matplotlib contour visualizations.

Updated on: 2026-03-25T22:09:58+05:30

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements