#! /bin/bash 
# Last edited on 2022-10-22 02:54:52 by stolfi

# Reads from stdin a file with least two numeric variables {X,Y}.
# Creates a scatterplot of those variables.
# Writes the plot as a PNG image to stdout, and displays it.

xcol="$1"; shift;  # Index of column in file with {X} values (hor axis).
xmin="$1"; shift;  # Min value of {X} to plot, or "" for auto.
xmax="$1"; shift;  # Max value of {X} to plot, or "" for auto.
xname="$1"; shift; # Name of {X} variable (label for hor axis).

ycol="$1"; shift;  # Index of column in file with {Y} values (ver axis).
ymin="$1"; shift;  # Min value of {Y} to plot, or "" for auto.
ymax="$1"; shift;  # Max value of {Y} to plot, or "" for auto.
yname="$1"; shift; # Name of {Y} variable (label for ver axis).

tmp="/tmp/$$"

tfile="${tmp}-f.png"
pfile="${tmp}-r.png"
dfile="${tmp}-d.dat"

cat > ${dfile}

export GDFONTPATH=${STOLFILOCAL}/ttf

gnuplot -background white <<EOF
  set term png medium size 1200,1200 font "courbd,18"
  set output "${tfile}"
  set xrange [${xmin}:${xmax}]
  set yrange [${ymin}:${ymax}]
  set key top left
  set xzeroaxis
  set yzeroaxis
  set xlabel "${xname}"
  set ylabel "${yname}"
  xcol = ${xcol}
  ycol = ${ycol}
  plot "${dfile}" using (column(xcol)):(column(ycol)) notitle with points pt 7 ps 1.5 lc rgb '#008800'
EOF

rm ${dfile}

if [[ -s ${tfile} ]]; then
  # Scale down the image for anti-aliasing:
  convert -resize '50%' ${tfile} ${pfile}
  display "${pfile}"
  cat ${pfile}
  rm ${tfile} ${pfile}
else
  echo "** plot failed" 1>&2
  rm -f ${tfile} # In case it exists but is empty.
  exit 1
fi
