Plot Multiple Lines of Different Lengths in Matplotlib

I often encounter scenarios where I need to visualize multiple data series on the same plot. However, one common challenge is when these data series have different lengths. Plotting multiple lines of different lengths in Matplotlib can be tricky if you’re not familiar with the right approach.

In this article, I will share practical methods to plot multiple lines of different lengths using Matplotlib. Whether you’re analyzing sales data from different US states or comparing time series with missing data points, these techniques will help you create clear and effective visualizations.

Let’s get in!

Method to Plot Lines of Different Lengths

In real-world data analysis, especially with US-based datasets like state-wise sales, economic indicators, or weather data, it’s common to have time series or sequences of different lengths. For example, you might have quarterly sales data for California spanning 12 quarters, but data for Texas only for 8 quarters.

Plotting these lines together helps compare trends visually, but handling different lengths requires some care to avoid errors or misleading plots.

Method 1: Plot Lines Individually with Explicit X and Y Data

The most straightforward way to plot multiple lines of different lengths is to plot each line individually by specifying its own x and y data arrays.

Here’s a practical example where I plot quarterly sales data for three US states, each with different numbers of data points:

import matplotlib.pyplot as plt

# Quarterly sales data (in thousands of dollars)
california_sales = [250, 270, 300, 320, 310, 330, 350, 370, 390, 400, 420, 430]
texas_sales = [200, 220, 230, 240, 250, 260, 270, 280]  # fewer quarters
florida_sales = [150, 160, 170, 180, 190, 200, 210, 220, 230, 240]  # intermediate length

# Corresponding quarters (x-axis)
california_quarters = list(range(1, len(california_sales) + 1))
texas_quarters = list(range(1, len(texas_sales) + 1))
florida_quarters = list(range(1, len(florida_sales) + 1))

plt.figure(figsize=(10, 6))

plt.plot(california_quarters, california_sales, marker='o', label='California')
plt.plot(texas_quarters, texas_sales, marker='s', label='Texas')
plt.plot(florida_quarters, florida_sales, marker='^', label='Florida')

plt.title('Quarterly Sales by State')
plt.xlabel('Quarter')
plt.ylabel('Sales (in $1000)')
plt.legend()
plt.grid(True)
plt.show()

You can see the output in the screenshot below.

Matplotlib Plot Multiple Lines of Different Lengths

Explanation

  • Each state’s sales data is paired with its x-axis values (quarters).
  • This avoids issues that arise if you try to plot arrays of different lengths without specifying x-values.
  • Markers differentiate the lines visually.

This method is simple and effective when you have explicit x-values for each dataset.

Check out Horizontal Line Matplotlib

Method 2: Use Pandas DataFrame with NaN for Missing Values

Sometimes, your data might be in a tabular format where some series are shorter. You can create a Pandas DataFrame and use NaN for missing values. Matplotlib will automatically handle these gaps.

Here’s an example:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create a DataFrame with sales data
data = {
    'Quarter': list(range(1, 13)),
    'California': [250, 270, 300, 320, 310, 330, 350, 370, 390, 400, 420, 430],
    'Texas': [200, 220, 230, 240, 250, 260, 270, 280] + [np.nan]*4,
    'Florida': [150, 160, 170, 180, 190, 200, 210, 220, 230, 240] + [np.nan]*2
}

df = pd.DataFrame(data)

plt.figure(figsize=(10, 6))

plt.plot(df['Quarter'], df['California'], marker='o', label='California')
plt.plot(df['Quarter'], df['Texas'], marker='s', label='Texas')
plt.plot(df['Quarter'], df['Florida'], marker='^', label='Florida')

plt.title('Quarterly Sales by State (with NaNs)')
plt.xlabel('Quarter')
plt.ylabel('Sales (in $1000)')
plt.legend()
plt.grid(True)
plt.show()

You can see the output in the screenshot below.

Plot Multiple Lines of Different Lengths Matplotlib

Explanation

  • Missing data points for Texas and Florida are filled with NaN.
  • Matplotlib skips plotting these points, so the lines end where data is available.
  • This approach is great if you want to keep a uniform x-axis across all lines.

Method 3: Plot Multiple Lines Using a Loop for Efficiency

When working with many datasets, manually plotting each line can be tedious. You can store your data in a dictionary and loop through it to plot each line.

Here’s how I do it with different-length data series:

import matplotlib.pyplot as plt

sales_data = {
    'California': [250, 270, 300, 320, 310, 330, 350, 370, 390, 400, 420, 430],
    'Texas': [200, 220, 230, 240, 250, 260, 270, 280],
    'Florida': [150, 160, 170, 180, 190, 200, 210, 220, 230, 240]
}

plt.figure(figsize=(10, 6))

for state, sales in sales_data.items():
    quarters = list(range(1, len(sales) + 1))
    plt.plot(quarters, sales, marker='o', label=state)

plt.title('Quarterly Sales by State (Looped Plot)')
plt.xlabel('Quarter')
plt.ylabel('Sales (in $1000)')
plt.legend()
plt.grid(True)
plt.show()

You can see the output in the screenshot below.

Plot Multiple Lines of Different Lengths in Matplotlib

Explanation

  • This method scales well with many datasets.
  • Each line gets its x-values based on the data length.
  • The loop keeps the code clean and maintainable.

Read Stacked Bar Chart Matplotlib

Tips for Handling Different Lengths in Matplotlib

  • Always specify x-values explicitly when y-values have varying lengths.
  • Use NaN values in Pandas DataFrames to align data on a common x-axis.
  • Customize markers and line styles for better distinction.
  • Add legends and gridlines for clarity.
  • Label axes clearly, especially when using time or sequential data.

Conclusion

Plotting multiple lines of different lengths in Matplotlib is easy once you understand how to manage your x and y data. Whether you prefer plotting each line individually, using Pandas DataFrames with NaN for missing data or looping through datasets, these methods will help you create insightful visualizations.

I hope you find these techniques useful in your data projects, especially when working with diverse US-based datasets.

You may like to read other Matplotlib-related articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.