Skip to content

Instantly share code, notes, and snippets.

@bbeck
Created May 2, 2013 14:42
Show Gist options
  • Save bbeck/5502671 to your computer and use it in GitHub Desktop.
Save bbeck/5502671 to your computer and use it in GitHub Desktop.
Shell front end that enables you to use Gnuplot from a shell pipeline
#!/bin/bash
set -o errexit
set -o nounset
function data() {
# f(x) = x^2 + noise(500)
# g(x) = x^2 + noise(2500)
for i in {1..100}; do
fx=$((i*i + $RANDOM%1000 - 500))
gx=$((i*i + $RANDOM%5000 - 2500))
echo $i, $fx, $gx
done
}
# Normal plot x, f(x)
data | plot using 1:2
# Connect the points
data | plot using 1:2 with lines
# Plot 2 data series on the same graph (same y-axis)
data | plot using 1:2 with lines, using 1:3 with points
# Label the plot and series
data | plot --title "foo vs. bar" using 1:2 with lines title "'foo'", using 1:3 with points title "'bar'"
# Save the output to a file
data | plot --output png --title "foo vs. bar" using 1:2 with lines title "'foo'", using 1:3 with points title "'bar'" > foo_vs_bar.png
#!/bin/bash
set -o errexit
set -o nounset
function main() {
local data=$(mktemp "data.XXXXXX")
local script=$(mktemp "script.XXXXXX")
# Make sure we always cleanup...
trap "{ rm -f '${data}' '${script}' >/dev/null 2>&1; }" EXIT
# Read the data from standard input and save it...
cat - > "${data}"
# Parse the command line arguments into a GNU Plot script. The arguments that
# start with -- get translated to set statements. Anything else gets emitted
# as-is to the script.
while [[ $# -gt 0 ]]; do
case "${1}" in
--*) echo "set ${1:2} '${2}'" >> "${script}"; shift;;
--) shift; break;;
*) break;;
esac
shift
done
# Build the plot command from the remaining arguments. Anytime we encounter
# the word using, we need to prepend it with the data filename.
echo -n "plot " >> "${script}"
while [[ $# -gt 0 ]]; do
case "${1}" in
using) echo -n "'${data}' using " >> "${script}";;
*) echo -n "${1} " >> "${script}";;
esac
shift
done
# Plot
gnuplot --persist "${script}"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment