Back to Home

Building graphs from CSV in Python matplotlib

The article describes scripts for building 2D graphs from CSV with matplotlib. Examples: basic plot, adding illuminance threshold, grid, legend. Advantages and package installation.

Graphs from CSV: matplotlib in Python with examples
Advertisement 728x90

Visualizing CSV Data with Matplotlib in Python

A Python script using the matplotlib library lets you quickly create visualizations from CSV files. This example uses a file called LiLog.csv with columns for row number, light level (Lx), temperature, time, date, and Unix timestamp. The graph plots timestamp (column 6) on the X-axis and light level (column 2) on the Y-axis.

You'll need Python 3+, matplotlib, and the built-in csv module. Check your Python interpreter with where python and use a clean install, avoiding bundles from Cygwin or Inkscape.

Install the dependencies:

Google AdInline article slot
pip install matplotlib numpy

Basic Script for 2D Line Graph

This code loads the data, parses the CSV, and draws a line:

import matplotlib.pyplot as plt
import csv

X = []
Y = []

with open('LiLog.csv', 'r') as datafile:
    plotting = csv.reader(datafile, delimiter=',')  # Set to comma for this example
    
    for ROWS in plotting:
        X.append(float(ROWS[5]))
        Y.append(float(ROWS[1]))

plt.plot(X, Y)
plt.title('Line Graph using CSV')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

The X and Y lists are filled with float values from the specified columns. csv.reader handles the delimiter (comma in this case—check your file). plt.plot draws the line, and show() opens the window.

Advanced Graph with Threshold Line and Annotations

Add a horizontal threshold line (63 Lx), grid, legend, and rotated labels:

Google AdInline article slot
import matplotlib.pyplot as plt
import csv

X = []
Y = []

with open('LiLog.csv', 'r') as datafile:
    plotting = csv.reader(datafile, delimiter=',')
    
    for ROWS in plotting:
        X.append(float(ROWS[5]))
        Y.append(float(ROWS[1]))

threshold = 63.0
T = [threshold] * len(Y)

plt.plot(X, Y)
plt.plot(X, T)
plt.title('Illumination change')
plt.xlabel('Time,[s]')
plt.ylabel('Light level, [Lx]')
plt.grid()
plt.xticks(rotation=-90)
plt.legend(['illumination', f'threshold {threshold} Lx'])
plt.show()

Check array lengths with print(len(X), len(Y)). Data types are list[float]. Interactive features include zoom and pan via the matplotlib window toolbar.

Dependencies and Installation

List installed packages: pip freeze. Typical matplotlib output:

  • contourpy==1.3.3
  • cycler==0.12.1
  • fonttools==4.62.1
  • kiwisolver==1.5.0
  • matplotlib==3.10.8
  • numpy==2.4.4

Install individually: pip install matplotlib numpy.

Google AdInline article slot

Why Matplotlib Rocks for Data Visualization

  • Free and open-source.
  • Interactive: zoom, save as PNG, customize axes and grids.
  • Cross-platform: Windows, Linux (with GUI).
  • Package into EXE with PyInstaller for easy sharing.
  • Minimal footprint: just a .py file.
  • Headless automation: run from command line without GUI.

Limitations

  • Real-time plotting (e.g., COM/TCP streams) needs threading or FuncAnimation.
  • Large datasets (>1M points) may slow down—optimize with numpy arrays.

Key Tips

  • Use numpy for arrays: X = np.array(X) speeds up plotting.
  • CSV delimiter: try delimiter=',' or ';', or switch to pandas for complex files.
  • Axes labels: plt.xlabel, plt.ylabel with units (s, Lx).
  • Legend: plt.legend(['data', 'threshold']) for multiple lines.
  • Grid: plt.grid() boosts readability.

Python + matplotlib is the go-to combo for quick visualizations of experimental data from CSV files. Perfect for sensor log analysis, like light levels over time.

— Editorial Team

Advertisement 728x90

Read Next