xxxxxxxxxx
94
// Basic line graph example with csv input and axis labels
//
// Here, we are visualizing my runs over the past decade.
// The CSV format is:
// Year,Total Runs,Total Distance (miles),Avg Distance (mi)
//
// By Professor Jon E. Froehlich
// https://makeabilitylab.cs.uw.edu/
//
let table;
let maxNumOfRuns;
function preload(){
table = loadTable("data/froehlich_run_stats.csv", "csv", "header");
}
function setup() {
createCanvas(500, 400);
// Print values from table
print(table.getRowCount() + ' total rows in table');
print(table.getColumnCount() + ' total columns in table');
print(table.getColumn('Year'));
// Get and print the max num of 3 pters made
maxNumOfRuns = max(table.getColumn('Total Runs'));
print("Max num of runs " + maxNumOfRuns);
}
function draw() {
background(220);
// Set some visual design constants
const rectWidth = 25; // in pixels
const graphHeight = 320; // height of our graph
const xMargin = 50;
const yMargin = 50;
const xSpaceBetweenBars = 12;
let lastPt = null;
for(let i = 0; i < table.getRowCount(); i++){
// Translate value from value range to pixel range
const numRuns = table.getNum(i, 1);
const barHeight = map(numRuns, 0, maxNumOfRuns, 0, graphHeight);
const yBar = graphHeight - barHeight; // top y loc of bar
const xBar = xMargin + i * (rectWidth + xSpaceBetweenBars); // x loc of bar
// Draw a circle at the point
fill(0, 0, 180);
noStroke();
const xPt = xBar + rectWidth / 2.0;
const yPt = yBar + yMargin;
circle(xPt, yPt, 8);
if(i > 0){
stroke(0, 0, 180);
line(lastPt.x, lastPt.y, xPt, yPt);
}
// Draw the year under the bar
const yYearText = yBar + barHeight + yMargin + textSize();
fill(0);
noStroke();
text(table.getString(i, 0), xBar, yYearText);
lastPt = {
x: xPt,
y: yPt
};
}
// Draw the y tick marks
const yTickMarkStep = 50;
for(let yTickMarkVal = 0; yTickMarkVal < maxNumOfRuns; yTickMarkVal += yTickMarkStep){
const yTickMark = yMargin + graphHeight - map(yTickMarkVal, 0, maxNumOfRuns, 0, graphHeight);
const yTickMarkLbl = str(yTickMarkVal);
const yTickMarkLblWidth = textWidth(yTickMarkLbl);
const xTickMark = xMargin - yTickMarkLblWidth - 15;
noStroke();
text(yTickMarkLbl, xTickMark, yTickMark + textSize() * 0.35);
stroke(0);
line(xMargin - 10, yTickMark, xMargin - 6, yTickMark);
}
// Draw graph title
push();
textSize(20);
textAlign(CENTER, TOP);
text("Total Runs Per Year", width / 2, 10);
pop();
}