Data: Arrays

Store and render datasets with array-based loops.

Example 1: Bars from Numbers

Code

const values = [12, 35, 24, 48, 18, 30, 44, 28];

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(252);
  const w = width / values.length;
  for (let i = 0; i < values.length; i++) {
    const h = map(values[i], 0, 50, 0, 280);
    fill(255, 45, 140);
    rect(i * w + 10, height - h - 30, w - 20, h, 6);
  }
}

Try this: Replace hardcoded data with random generation each reset.

Open sketch in new tab

Example 2: Dot Plot

Code

let nums = [4, 9, 2, 14, 7, 10, 1, 12, 6, 3, 11, 8, 5, 13];

function setup() {
  createCanvas(400, 400);
  textAlign(CENTER);
}

function draw() {
  background(255);
  for (let i = 0; i < nums.length; i++) {
    let x = map(i, 0, nums.length - 1, 40, width - 40);
    let y = map(nums[i], 0, 15, height - 40, 40);
    fill(255, 45, 140);
    noStroke();
    circle(x, y, 14);
    fill(30);
    text(nums[i], x, y - 14);
  }
}

Try this: Sort the array to compare unsorted vs sorted visual output.

Open sketch in new tab

Resources