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.
pip install matplotlib
Python code
35 linesimport 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
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
- Use `pandas.read_csv` and `pandas.DataFrame.plot` for a more concise alternative with built-in data handling.
- 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
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
- Benchmark File Read and Write Speed in Python medium
Keep learning
Related tutorials and quizzes for this topic.