How to use csv data and draw in p5.js?

Member

by darion , in category: Javascript , 2 months ago

How to use csv data and draw in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 2 months ago

@darion 

To use CSV data and draw in p5.js, you can follow these steps:

  1. Load the CSV data using the loadTable() function in p5.js. For example:
1
2
3
4
5
let table;

function preload() {
  table = loadTable('data.csv', 'csv', 'header');
}


Make sure to replace 'data.csv' with the path to your CSV file.

  1. Parse the data in the CSV file and store it in a variable that can be accessed later. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let data = [];

function setup() {
  for (let i = 0; i < table.getRowCount(); i++) {
    let row = table.getRow(i);
    let x = row.getNum('x');
    let y = row.getNum('y');
    data.push({ x, y });
  }
}


  1. Use the data to draw shapes, lines, or other elements on the canvas in the draw() function. For example, you can draw circles at the coordinates specified in the CSV file:
1
2
3
4
5
6
7
8
function draw() {
  background(255);

  for (let i = 0; i < data.length; i++) {
    let { x, y } = data[i];
    ellipse(x, y, 10, 10);
  }
}


  1. Run your sketch in the browser and you should see the data from the CSV file being used to draw shapes on the canvas.


These are the basic steps to use CSV data and draw in p5.js. Depending on the complexity of your data and visualization, you may need to adjust and customize your code accordingly.