tutorial 1.5:

Importing CSV data in Processing Part 2

In this example we'll build on example 1.4 by looping through all the values contained in a CSV (comma-separated values) file, and will use those values to apply colours for each circle.

1) Start by copying and pasting the following code into a new empty sketch:

Make sure that you give it a new title / subtitle in the correct comment syntax

  Tutorial 1.4 importing csv data. Mark Meagher and Adam Park Nov 2014

Table myCSV; //declare a table object that will contain the CSV
String myDataFile = "UK_climate.csv";
int myColorRed;
int myColorGreen;
int myColorBlue;
int myValue;

void setup() {
  size(400, 450); // set the size of the display window
  myCSV = loadTable(myDataFile, "header"); //this loads the data from the CSV into the Table object. So long as your data isn't changing, this only needs to happen once

void draw() {

2) Next we'll create some geometry based on the data contained in the CSV.

Copy the following code into a new tab called 'functions':

void initForm() {

  int numColumns = myCSV.getColumnCount();
  int myRadius = 5;
  int myX = 10;
  int myY = 10;
  int rowCount = 0;

  for (TableRow row : myCSV.rows ()) {
    myY = 10 + (12*rowCount);
    for (int i=1; i<numColumns; i++) {
      myX = 10 + (12*i);
      int myValue = row.getInt(i);
      println("the value is " + myValue);

      if (myValue<1) {
        myColorRed = 0;
        myColorGreen = 0;
        myColorBlue = 200;
      } else if (myValue<5) {
        myColorRed = 200;
        myColorGreen = 200;
        myColorBlue = 200;
      } else if (myValue<8) {
        myColorRed = 150;
        myColorGreen = 150;
        myColorBlue = 150;
      } else if (myValue<10) {        
        myColorRed = 80;
        myColorGreen = 80;
        myColorBlue = 80;
      } else if (myValue>=10) {
        myColorRed = 200;
        myColorGreen = 0;
        myColorBlue = 0;
      makeCircle(myRadius, myColorRed, myColorGreen, myColorBlue, myX, myY);

This function has been expanded from example 1.4: now there are two 'nested' loops, the first of which loops through the rows and the second loops through all the values in each row. A colour is assigned based on the value in each cell of the table, and this colour value is then passed to the 'makeCircle' function along with the current X and Y position. Colour is now defined using three variables, to allow RGB colour to be used.

The makeCircle function also has to be modified to include RGB color:

void makeCircle(int myRadius, int myColorRed, int myColorGreen, int myColorBlue, int myX, int myY) {
  stroke (myColorRed,myColorGreen,myColorBlue);
  ellipse(myX, myY, myRadius, myRadius);

You can download the code from this example here.


How could you highlight the minimum and maximum elements stored in the array ?

How could you sort the elements in the array from smallest to largest ?