Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Automatically Generate Charts from CSV Files with One Command

Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Requires third-party packages — install first
pip install matplotlib

Python code

35 lines
Python 3.9+
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt

def generate_chart(csv_path: str) -> None:
    """Read a CSV file with headers and plot the first two numeric columns."""
    data = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.reader(f)
        headers = next(reader)
        for row in reader:
            try:
                x = float(row[0])
                y = float(row[1])
                data.append((x, y))
            except (ValueError, IndexError):
                continue
    if not data:
        print("No numeric data found.")
        return
    x_vals, y_vals = zip(*data)
    plt.plot(x_vals, y_vals, marker='o')
    plt.xlabel(headers[0] if headers else 'X')
    plt.ylabel(headers[1] if len(headers) > 1 else 'Y')
    plt.title(f"Chart from {Path(csv_path).name}")
    plt.grid(True)
    plt.savefig(Path(csv_path).with_suffix('.png'))
    print(f"Saved chart to {Path(csv_path).stem}.png")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <csv_file>")
        sys.exit(1)
    generate_chart(sys.argv[1])

Output

stdout
Saved chart to data.png

How it works

The script uses csv.reader to parse the CSV and skips rows that don't have numeric values in the first two columns. matplotlib.pyplot.plot draws a line chart with markers, and savefig writes the output to a file in the same directory as the input, replacing the extension with .png. Headers from the CSV are used for axis labels, and a grid is added for readability.

Common mistakes

  • Forgetting to install matplotlib with `pip install matplotlib` before running the script.
  • Not handling non-numeric or missing data, which causes the script to skip entire rows.
  • Assuming the CSV always has at least two columns without checking with try/except.

Variations

  1. Use `pandas.read_csv` and `pandas.DataFrame.plot` for a more concise alternative with built-in data handling.
  2. Add command-line flags with argparse to choose which columns to plot or customize the chart style.

Real-world use cases

  • Automatically generating daily sales trend charts from exported CSV reports in a cron job.
  • Plotting sensor readings from data log files during a hardware prototype debugging session.
  • Creating quick visual snapshots of CSV exports from database queries without opening a GUI tool.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.