#! /bin/bash
# Last edited on 2011-06-23 15:27:32 by stolfi

title="$1"; shift

# Plots the 2011 Brazilian PISA data by state

tmp="/tmp/$$"

datafile="${tmp}-d.txt"

cat \
  | sort -t'|' -b -k5,5gr -k1,1 \
  | gawk \
      ' BEGIN { FS= "|"; un = 1; }
        /^[A-Z][A-Z] [|]/ { 
          gsub(/[ ]*[|][ ]*/, "|", $0);
          gsub(/^[ ]+/, "", $0);
          gsub(/[ ]+$/, "", $0);
          uf = $1; md = $3; rd = $4; mt = $5; sc = $6;
          printf "%2d %5.3f %s %4.1f %4.1f %4.1f\n", un, -0.500, uf, 0, 0, 0;
          printf "%2d %5.3f %s %4.1f %4.1f %4.1f\n", un, -0.499, uf, rd, mt, sc;
          printf "%2d %5.3f %s %4.1f %4.1f %4.1f\n", un, 00.000, uf, rd, mt, sc;
          printf "%2d %5.3f %s %4.1f %4.1f %4.1f\n", un, +0.499, uf, rd, mt, sc;
          printf "%2d %5.3f %s %4.1f %4.1f %4.1f\n", un, +0.500, uf, 0, 0, 0;
          printf "\n";
          un++;
        }
      ' \
  > ${datafile}
  
width=2400
height=800

tempplot="${tmp}-t.png"
fullplot="${tmp}-f.png"
    
export GDFONTPATH=.

gnuplot <<EOF

set term png font arial 14 size ${width},${height}
set xrange [0.0:29.0]
set yrange [0.0:600.0]
set output "${tempplot}" 
set format x ""
set title "PISA - alunos de 15 anos - ${title}"

set grid ytics

disp(k) = 0.25*k
xbar(i,j,k) = (column(i) + 0.25*column(j)) + disp(k)
xlab(i,j,k) = (column(j) == 0.0 ? column(i) + disp(k) : 0/0)
ufname(k) = stringcolumn(k)

plot \
  "${datafile}" using (xbar(1,2,-1)):(column(5))       title "Matematica"  with filledcurves y1=0 lc rgb '#bbaa00', \
  "${datafile}" using (xbar(1,2,00)):(column(4))       title "Leitura"     with filledcurves y1=0 lc rgb '#446688', \
  "${datafile}" using (xbar(1,2,+1)):(column(6))       title "Ciencias"    with filledcurves y1=0 lc rgb '#33cc00', \
  "${datafile}" using (xlab(1,2,00)):(475):(ufname(3)) notitle with labels font "arial,18" tc rgb '#000000'
  
quit
EOF

convert ${tempplot} -resize '50%' ${fullplot}

display ${fullplot}

cat ${fullplot}

rm -f ${tmp}-*


