How to extract data from a Matplotlib plot?

To extract data from a plot in matplotlib, we can use get_xdata() and get_ydata() methods. This is useful when you need to retrieve the underlying data points from an existing plot object.

Basic Data Extraction

The following example demonstrates how to extract x and y coordinates from a matplotlib plot ?

import numpy as np
from matplotlib import pyplot as plt

# Configure plot appearance
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
y = np.array([1, 3, 2, 5, 2, 3, 1])

# Create plot and store line object
curve, = plt.plot(y, c='red', lw=5)

print("Extracting data from plot....")

# Extract data using get_xdata() and get_ydata()
xdata = curve.get_xdata()
ydata = curve.get_ydata()

print("X data points for the plot is: ", xdata)
print("Y data points for the plot is: ", ydata)

plt.show()
Extracting data from plot....
X data points for the plot is: [0. 1. 2. 3. 4. 5. 6.]
Y data points for the plot is: [1 3 2 5 2 3 1]
0 1 2 3 4 5 0 1 2 3 4 5 6

Extracting Data from Multiple Lines

When working with multiple plot lines, you can extract data from each line separately ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
x = np.linspace(0, 10, 6)
y1 = np.sin(x)
y2 = np.cos(x)

# Create multiple plots
line1, = plt.plot(x, y1, 'b-', label='sin(x)', linewidth=3)
line2, = plt.plot(x, y2, 'g--', label='cos(x)', linewidth=3)

# Extract data from both lines
x1_data = line1.get_xdata()
y1_data = line1.get_ydata()
x2_data = line2.get_xdata()
y2_data = line2.get_ydata()

print("Line 1 (sin) - X data:", x1_data[:3])  # Show first 3 points
print("Line 1 (sin) - Y data:", y1_data[:3])
print("Line 2 (cos) - X data:", x2_data[:3])
print("Line 2 (cos) - Y data:", y2_data[:3])

plt.legend()
plt.grid(True)
plt.show()
Line 1 (sin) - X data: [0. 2. 4.]
Line 1 (sin) - Y data: [ 0.          0.90929743 -0.7568025 ]
Line 2 (cos) - X data: [0. 2. 4.]
Line 2 (cos) - Y data: [ 1.         -0.41614684 -0.65364362]

Key Points

  • get_xdata() returns the x-coordinates as a NumPy array
  • get_ydata() returns the y-coordinates as a NumPy array
  • You must store the plot object (line) to access these methods
  • Works with any matplotlib line plot, including multiple lines
  • Useful for data analysis, validation, or saving plot data

Conclusion

Use get_xdata() and get_ydata() methods to extract underlying data points from matplotlib plot objects. This technique is essential for data retrieval and analysis from existing plots.

Updated on: 2026-03-25T21:08:42+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements