Quick plotting

Comments
Bookmark and Share

While I was writing my last Mythbusters blog post, I realized that it’d be really useful to have a “quick and dirty” plotting program — one that just takes the output of another program and plots it, no questions asked. Actually, let me rephrase that: I knew it would be useful, it just never occurred to me that I don’t have one. Most of the common plotting programs people tend to use, like GNUplot, expect to be configured with the format and syntax and display options and all that junk that you don’t really care about when you just want to turn numbers into a picture.

If you have GNUplot installed, here’s a little script to do just that:

#!/bin/bash

using=""

shopt -s extglob
if [[ "$1" == +([[:digit:]])*(,+([[:digit:]])) ]]; then
        using="using ${1//,/:} "
        shift
fi
shopt -u extglob

plotopts=""

if [[ "$*" == *title* ]]; then
        next_is_title=""
        for word; do
                if [[ -n "$next_is_title" ]]; then
                        plotopts="$plotopts title '$word'"
                        next_is_title=""
                        continue
                fi
                if [[ "$word" == "title" ]]; then
                        next_is_title="1"
                else
                        plotopts="$plotopts $word"
                fi
        done
else
        plotopts="$* title 'STDIN'"
fi

gnuplot -p -e "plot '-' ${using}${plotopts}"

Save it as plot, make it executable, and put it in your $PATH, and then you can run things like this:

calculation | plot

and you get a picture. calculation can be any program that produces output in the form

x1 y1
x2 y2
...

You can also pass any GNUplot options, like

calculation | plot using lp

to plot with lines and points, and there’s a special case in the script to give the graph a title, like

calculation | plot title 'My Graph!' using lp

It would probably make sense to add xlabel and ylabel options, but… I didn’t. I finished using the script before I needed them.