How to merge two existing Matplotlib plots into one plot?

Matplotlib allows you to combine data from multiple plots into a single visualization. This is useful when you want to merge separate plot lines or analyze combined datasets.

Basic Plot Merging Example

Here's how to extract data from existing plots and combine them into one ?

import numpy as np
import matplotlib.pyplot as plt

# Configure figure settings
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

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

# Create first subplot with two separate plots
plt.subplot(211)
plt.plot(x, y1, color='red', linewidth=2, label='sin(x)')
plt.plot(x, y2, color='blue', linewidth=2, label='cos(x)')
plt.title('Original Separate Plots')
plt.legend()
plt.grid(True, alpha=0.3)

# Extract data from existing plots
X, Y = [], []

for lines in plt.gca().get_lines():
    for point_x, point_y in lines.get_xydata():
        X.append(point_x)
        Y.append(point_y)

# Sort the combined data by x-values
idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]

# Create second subplot with merged data
plt.subplot(212)
plt.plot(X, Y, color='green', linewidth=1, label='Merged Data')
plt.title('Merged Plot Data')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlabel('X values')
plt.ylabel('Y values')

plt.tight_layout()
plt.show()

Alternative Method: Direct Data Combination

You can also merge plots by directly combining the data arrays ?

import numpy as np
import matplotlib.pyplot as plt

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

# Method 1: Plot separately first
plt.figure(figsize=(12, 4))

plt.subplot(131)
plt.plot(x, y1, 'r-', label='sin(x)')
plt.title('Plot 1')
plt.legend()
plt.grid(True, alpha=0.3)

plt.subplot(132)
plt.plot(x, y2, 'b-', label='cos(x+2)')
plt.title('Plot 2')
plt.legend()
plt.grid(True, alpha=0.3)

# Method 2: Combine data directly
plt.subplot(133)
combined_x = np.concatenate([x, x])
combined_y = np.concatenate([y1, y2])

# Sort by x-values for proper line connection
sort_idx = np.argsort(combined_x)
combined_x = combined_x[sort_idx]
combined_y = combined_y[sort_idx]

plt.plot(combined_x, combined_y, 'g-', linewidth=1, label='Merged')
plt.title('Merged Plot')
plt.legend()
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Key Methods for Plot Merging

Method Use Case Advantage
get_lines().get_xydata() Extract from existing plots Works with any plotted data
np.concatenate() Combine data arrays directly More control over data
np.argsort() Sort merged data Ensures proper line connection

Practical Use Case

Merging multiple datasets from different sources ?

import numpy as np
import matplotlib.pyplot as plt

# Simulate data from different experiments
experiment1_x = np.array([1, 2, 3, 4, 5])
experiment1_y = np.array([2.1, 3.9, 6.2, 7.8, 10.1])

experiment2_x = np.array([5.5, 6, 7, 8, 9])
experiment2_y = np.array([10.5, 12.8, 15.1, 17.9, 20.2])

# Plot individual experiments
plt.figure(figsize=(10, 5))

plt.subplot(121)
plt.plot(experiment1_x, experiment1_y, 'ro-', label='Experiment 1')
plt.plot(experiment2_x, experiment2_y, 'bs-', label='Experiment 2')
plt.title('Separate Experiments')
plt.legend()
plt.grid(True, alpha=0.3)

# Merge experiments into single dataset
merged_x = np.concatenate([experiment1_x, experiment2_x])
merged_y = np.concatenate([experiment1_y, experiment2_y])

# Sort by x-values
sort_indices = np.argsort(merged_x)
merged_x = merged_x[sort_indices]
merged_y = merged_y[sort_indices]

plt.subplot(122)
plt.plot(merged_x, merged_y, 'g^-', label='Combined Data')
plt.title('Merged Experimental Data')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlabel('X values')
plt.ylabel('Y values')

plt.tight_layout()
plt.show()

Conclusion

Use get_lines().get_xydata() to extract data from existing plots, or np.concatenate() to merge data arrays directly. Always sort merged data with np.argsort() for proper visualization.

Updated on: 2026-03-26T00:02:32+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements