2025, Oct 17 21:00
Fix 'x and y must have same first dimension' in Matplotlib: 1D NumPy plotting with a proper x index
Learn why Matplotlib throws 'x and y must have same first dimension' when plotting a 1D NumPy array, and fix it by building a matching x index with np.arange.
When plotting a 1D NumPy array with Matplotlib, a common pitfall is giving x and y arrays of different lengths. If they don’t line up, Matplotlib raises a clear exception: x and y must have the same first dimension. Below is a minimal, real-world scenario that leads to this error and a straightforward way to resolve it.
Problem setup
The dataset contains 1800 ADC samples collected over 3 minutes at 10 Hz. The goal is to read values from a file, build a 1D NumPy array, and visualize it.
import matplotlib.pyplot as plt
import numpy as np
series = np.array
log_path = "MyValues.log"  # Replace with your actual path
samp_rate = 10
span_sec  = 180.0            # seconds
sample_total = int(span_sec * samp_rate)  # expected number of samples
try:
    with open(log_path, 'r') as fh:
        for row in fh:
            series = np.append(series, int(row.strip()))
except FileNotFoundError:
    print(f"Error: The file '{log_path}' was not found.")
except Exception as exc:
    print(f"An error occurred: {exc}")
 
print(len(series))
plt.figure(figsize=(10, 6))
plt.plot(sample_total, series, marker='o', linestyle='-', color='purple')
plt.title('Plot of 1D Array Data')
plt.xlabel('Index')
plt.ylabel('Value')
plt.grid(True)
plt.xticks(sample_total)
plt.show()What’s going wrong
The plotting call uses a scalar for the x-axis and a vector for the y-axis. Matplotlib expects both x and y to be sequences of the same length, or only y if you want indices generated automatically. Here, sample_total equals 1800, which is just a single number, not an array of indices. The same mistake happens in the xticks call: passing a single integer instead of a sequence of tick positions.
In other words, the y data contains many points, while the x input provides only one. That mismatch triggers the ValueError.
Solution: build a matching index for x
Construct a sequence for the x-axis that matches the length of your data. If you want index-based plotting, use np.arange over the length of the array. Also, read the file into a numeric vector first, then plot.
import matplotlib.pyplot as plt
import numpy as np
log_path = "MyValues.log"
samp_rate = 10
span_sec = 180.0
sample_total = int(span_sec * samp_rate)
try:
    with open(log_path, "r") as fh:
        readings = [int(row.strip()) for row in fh]
    data_vec = np.array(readings)
    # Optional sanity check against the expected sample count
    if len(data_vec) != sample_total:
        print(f"Expected {sample_total}, but got {len(data_vec)}")
    x_index = np.arange(len(data_vec))
    plt.figure(figsize=(10, 6))
    plt.plot(x_index, data_vec, marker='o', linestyle='-', color='purple')
    plt.title('Plot of 1D Array Data')
    plt.xlabel('Index')
    plt.ylabel('Value')
    plt.grid(True)
    plt.xticks(x_index)
    plt.show()
except FileNotFoundError:
    print(f"Error: The file '{log_path}' not exist.")
except Exception as err:
    print(f"error occurred: {err}")Why this matters
In time series and signal processing tasks—like inspecting raw ADC values before filter design—plotting is usually the first sanity check. If the x-axis doesn’t align with the data, you’ll misread trends or, worse, won’t be able to plot at all. Ensuring the x and y dimensions match avoids subtle debugging detours and makes subsequent steps, such as filter prototyping, far more reliable. It also helps validate assumptions: comparing the expected number of samples to what was actually loaded will quickly flag missing or extra lines in your data source.
Takeaways
Always feed Matplotlib a proper x vector when you don’t rely on implicit indexing. For index-based plots, np.arange over the length of the data is sufficient. If you also have a known sampling rate and duration, cross-check the expected sample count against the loaded data to verify integrity before visual analysis and filter design. With those small guardrails in place, plotting becomes predictable, and your signal processing workflow stays on track.
The article is based on a question from StackOverflow by Nimit Vachhani and an answer by Ranger.