Make a Multiline Plot from CSV File in Matplotlib

As a developer, I’ve worked on various data visualization projects. One of the most common tasks I encounter is plotting multiple lines on a single graph to compare trends or patterns. When your data comes from a CSV file, which is often the case, especially with real-world datasets like economic indicators or sales figures from US states, Matplotlib is the go-to library for creating clean and informative line plots.

In this tutorial, I’ll walk you through how to create a multiline plot directly from a CSV file using Matplotlib. I’ll share practical methods I use regularly, so you can efficiently visualize your data and gain insights quickly.

Prepare Your CSV Data

Before we jump into plotting, your CSV file should be organized with a clear structure. Typically, the first column contains the x-axis values (like dates or months), and each subsequent column holds data for a different series (e.g., different states or categories).

Here’s a simple example of what your CSV might look like:

MonthCaliforniaTexasNew York
Jan7.56.88.2
Feb7.36.78.0
Mar7.16.57.9

Method 1: Use Pandas and Matplotlib to Plot Multiple Lines

This is the method I use most often because it’s simple and leverages Pandas’ powerful data handling capabilities.

Step 1: Import Required Libraries

import pandas as pd
import matplotlib.pyplot as plt

Step 2: Load the CSV File

Assuming your CSV file is named us_state_unemployment.csv, you can load it like this:

data = pd.read_csv('us_state_unemployment.csv')

Step 3: Plot the Data

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

# Set the 'Month' column as x-axis
x = data['Month']

# Loop through each state column and plot it
for state in data.columns[1:]:
    plt.plot(x, data[state], marker='o', label=state)

plt.title('Monthly Unemployment Rates by State')
plt.xlabel('Month')
plt.ylabel('Unemployment Rate (%)')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

What’s Happening Here?

  • We read the CSV into a DataFrame.
  • We use the first column (Month) as the x-axis.
  • We loop through all other columns to plot each state’s unemployment rate.
  • Markers (marker='o') help identify data points.
  • The legend helps differentiate each line.
  • Rotating x-axis labels improves readability.

I executed the above example code and added the screenshot below.

Multiline Plot from CSV File in Matplotlib

Method 2: Use CSV Module and Matplotlib (Without Pandas)

Sometimes you might want to avoid external dependencies like Pandas. Here’s how to do it with Python’s built-in csv module.

Step 1: Import Libraries

import csv
import matplotlib.pyplot as plt

Step 2: Read CSV and Organize Data

with open('us_state_unemployment.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    headers = next(reader)

    months = []
    data_dict = {header: [] for header in headers[1:]}

    for row in reader:
        months.append(row[0])
        for i, value in enumerate(row[1:], start=1):
            data_dict[headers[i]].append(float(value))

Step 3: Plot the Data

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

for state, values in data_dict.items():
    plt.plot(months, values, marker='o', label=state)

plt.title('Monthly Unemployment Rates by State')
plt.xlabel('Month')
plt.ylabel('Unemployment Rate (%)')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

Make a Multiline Plot from CSV File in Matplotlib

Read Matplotlib Plotting Multiple Lines in 3D

Tips for Better Multiline Plots

  • Choose contrasting colors: Matplotlib automatically cycles colors, but you can customize for clarity.
  • Add markers: Helps distinguish lines, especially when printed in grayscale.
  • Use legends: Always label your lines to avoid confusion.
  • Adjust figure size: A wider figure often improves readability for many lines.
  • Rotate x-axis labels: Prevents overlap when labels are long (like month names).

Creating multiline plots from CSV files is a fundamental skill for any Python developer working with data, especially when analyzing trends across multiple categories like US states or product lines. Using Pandas with Matplotlib is my preferred approach for its simplicity and power, but the CSV module method works well when you want to keep dependencies minimal.

By following the steps above, you can quickly turn raw CSV data into insightful visualizations that help you make data-driven decisions.

If you want to dive deeper into plotting multiple lines or explore subplots, Matplotlib has plenty of options to customize your visuals to your exact needs.

You may 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.