Plotting two different arrays of different lengths in matplotlib

When plotting data in matplotlib, you often need to plot arrays of different lengths on the same graph. This is useful for comparing datasets with different sampling rates or time periods.

Steps to Plot Arrays of Different Lengths

  • Set up matplotlib figure configuration
  • Create arrays of different lengths using NumPy
  • Use the plot() method for each array with its corresponding x-values
  • Display the plot using show()

Example

Let's create two datasets with different lengths and plot them together ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure configuration
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create first dataset with 100 points
y1 = (np.random.random(100) - 0.5).cumsum()
x1 = np.linspace(0, 1, 100)

# Create second dataset with 10 points (averaged from first)
y2 = y1.reshape(-1, 10).mean(axis=1)
x2 = np.linspace(0, 1, 10)

# Plot both datasets
plt.plot(x1, y1, label='Original Data (100 points)')
plt.plot(x2, y2, 'ro-', label='Averaged Data (10 points)')

# Add labels and legend
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()

plt.show()

How It Works

The code creates two arrays:

  • Array 1: 100 random cumulative data points
  • Array 2: 10 points created by averaging every 10 values from the first array

Both arrays are plotted on the same axes, with different x-coordinates that match their respective lengths.

Key Points

  • Each array must have corresponding x-values of the same length
  • Use np.linspace() to create evenly spaced x-coordinates
  • Multiple plot() calls automatically use different colors
  • Add labels and legends to distinguish between datasets

Alternative Example with Random Data

Here's another example using completely different datasets ?

import numpy as np
import matplotlib.pyplot as plt

# First array - 50 points
x1 = np.linspace(0, 10, 50)
y1 = np.sin(x1)

# Second array - 20 points  
x2 = np.linspace(0, 10, 20)
y2 = np.cos(x2) * 1.5

# Plot both arrays
plt.figure(figsize=(8, 4))
plt.plot(x1, y1, 'b-', label='Sine wave (50 points)')
plt.plot(x2, y2, 'ro-', label='Cosine wave (20 points)')

plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Plotting Arrays of Different Lengths')
plt.legend()
plt.grid(True, alpha=0.3)

plt.show()

Conclusion

Plotting arrays of different lengths in matplotlib is straightforward - just ensure each array has matching x-coordinates of the same length. Use labels and legends to clearly distinguish between your datasets for better visualization.

Updated on: 2026-03-26T02:35:37+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements