Plot Multiple Graphs Generated Inside a For Loop in Matplotlib

If you’ve ever worked with data visualization in Python, you know how often you need to plot multiple graphs dynamically. It’s especially useful when dealing with datasets that change over time or when you want to visualize multiple categories or regions, like tracking sales trends across different US states.

In this tutorial, I’ll walk you through how to generate and plot multiple graphs inside a for loop using Matplotlib. I’ll share different methods based on my experience, so you can pick the one that fits your needs best.

Methods to Plot Multiple Graphs Inside a For Loop

Imagine you have monthly sales data for several states like California, Texas, and New York. Instead of manually creating a plot for each state, looping through your data and plotting inside a for loop saves time and makes your code scalable. This approach also helps when you want to automate report generation or build dashboards.

Method 1: Plot Multiple Lines on the Same Graph Inside a For Loop

The simplest way to plot multiple lines generated inside a for loop is to plot all lines on the same figure. This is useful when you want to compare trends side by side.

Here’s an example where I plot monthly sales for three states on one graph:

import matplotlib.pyplot as plt
import numpy as np

# Sample data: Monthly sales (in thousands) for 3 states
states = ['California', 'Texas', 'New York']
months = np.arange(1, 13)
sales_data = {
    'California': np.random.randint(50, 150, size=12),
    'Texas': np.random.randint(40, 130, size=12),
    'New York': np.random.randint(30, 120, size=12)
}

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

for state in states:
    plt.plot(months, sales_data[state], marker='o', label=state)

plt.title('Monthly Sales Comparison (in thousands) - 2025')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.xticks(months)
plt.legend()
plt.grid(True)
plt.show()

You can see the output in the screenshot below.

Matplotlib Multiple Graphs Generated Inside a For Loop

In this code, the for loop iterates over each state and plots its sales data on the same figure. This method gives a clear comparative view.

Method 2: Create Separate Plots for Each Dataset Inside a For Loop

Sometimes, you want to generate individual plots for each category, say, one graph per state. This is especially helpful for detailed analysis or when you want to save each plot separately.

Here’s how I do it:

import matplotlib.pyplot as plt
import numpy as np

states = ['California', 'Texas', 'New York']
months = np.arange(1, 13)
sales_data = {
    'California': np.random.randint(50, 150, size=12),
    'Texas': np.random.randint(40, 130, size=12),
    'New York': np.random.randint(30, 120, size=12)
}

for state in states:
    plt.figure(figsize=(8, 5))
    plt.plot(months, sales_data[state], marker='s', color='tab:blue')
    plt.title(f'Monthly Sales in {state} - 2025')
    plt.xlabel('Month')
    plt.ylabel('Sales (in thousands)')
    plt.xticks(months)
    plt.grid(True)
    plt.tight_layout()
    plt.show()

You can see the output in the screenshot below.

Multiple Graphs Generated Inside a For Loop Matplotlib

In this method, each iteration creates a new figure, plots the data, and displays it. You can also save these plots using plt.savefig() if you want to keep them for reports.

Method 3: Use Subplots to Display Multiple Graphs in One Figure

When you want to present multiple plots neatly in a single window, subplots are your friend. I often use this approach for dashboards or presentations.

Here’s how to plot multiple sales graphs for different states using subplots in a for loop:

import matplotlib.pyplot as plt
import numpy as np

states = ['California', 'Texas', 'New York']
months = np.arange(1, 13)
sales_data = {
    'California': np.random.randint(50, 150, size=12),
    'Texas': np.random.randint(40, 130, size=12),
    'New York': np.random.randint(30, 120, size=12)
}

fig, axs = plt.subplots(len(states), 1, figsize=(10, 12), sharex=True)

for i, state in enumerate(states):
    axs[i].plot(months, sales_data[state], marker='^', color='tab:green')
    axs[i].set_title(f'Monthly Sales in {state} - 2025')
    axs[i].set_ylabel('Sales (k)')
    axs[i].grid(True)

axs[-1].set_xlabel('Month')
plt.xticks(months)
plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Plot Multiple Graphs Generated Inside a For Loop in Matplotlib

This way, you get a clean, organized view of each state’s sales in separate panels stacked vertically.

Read Matplotlib Unknown Projection ‘3d’

Tips for Plotting Multiple Graphs in Loops

  • Use meaningful labels and titles: This helps when you’re comparing multiple plots.
  • Choose distinct markers or colors: It makes your plots easier to differentiate.
  • Manage figure size and layout: Use figsize and tight_layout() to avoid overlapping elements.
  • Save plots programmatically: Use plt.savefig() inside the loop if you want to generate reports automatically.

Conclusion

Plotting multiple plots inside a for loop is a powerful technique that saves time and makes your visualization scalable. Whether you want all lines on one graph, separate figures, or neatly arranged subplots, Python’s Matplotlib has you covered.

With real-world datasets like sales across US states, these methods help you quickly generate insights and share your findings effectively. Try these approaches, tweak them for your data, and you’ll become more efficient in your data visualization tasks.

If you want to dive deeper, I recommend exploring Matplotlib’s customization options to make your plots even more impactful.

Happy plotting!

You may also read:

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.