DEV Community

Cover image for Make a bar graph in P5.js
Ivy Chen
Ivy Chen

Posted on

Make a bar graph in P5.js

I came back from Taiwan after 6 months abroad a week ago. Naturally, I've been missing the food, the social life, the streets, and all the non-pandemic lifestyle there. So I decided to take a look at the Open Data Taiwan site and see if there's any interesting dataset that I can play around with.

This was a fun but also challenging 3-day data visualization project made in p5.js. After lots of debugging sessions and referencing different Youtube videos, I ended up figuring out by sticking to this creative course that I've been taking in Chinese.

In this tutorial, I will take you through the steps of making a bar chart in P5.js, a JavaScript library for creative coding. P5.js is easily accessible to everyone with its in-browser text editor and rich documentation of examples / references. We will be using OpenProcessing for this project, a platform for sharing your creative coding work.

Disclaimer: a fraction of the code will be in Chinese characters because the dataset from the Taiwanese government website is in Chinese.

Choose a dataset
You can choose any dataset that are open source online. There's this https://github.com/dariusk/corpora repository of interesting data in JSON format. I downloaded this CSV file from Open Data Taiwan, then used this link https://csvjson.com/ to translate the CSV file to JSON file. Save it and now we can move to to coding!

Load the JSON file
On OpenProcessing, create a new sketch and save it. Then click on the 3 dots menu bar and click on the files tab to upload your JSON file. Above your default setup() and draw() functions, declare a variable and assign it the file name in the preload() function.

var data 

function preload() {
    data = loadJSON("taiwan-jobs-income.json");
}
Enter fullscreen mode Exit fullscreen mode

Transform JSON to array of objects
Put this in the setup() to transform JSON into an array of objects so we can easily access them later. Now we're done with all that we have to write in setup()

data = Object.values(data);
Enter fullscreen mode Exit fullscreen mode

Change background color
In setup(), I changed the background to this dark blue color.

background("#182066");
Enter fullscreen mode Exit fullscreen mode

Drawing the bar graph
Now, moving into draw(), we will be using a for loop to put almost everything inside it. First you want to set up the for loop and translate the starting point of the graph 50 points to the right.

for(var i = 0; i <data.length; i++){
        translate(50,0);
    }
Enter fullscreen mode Exit fullscreen mode

Then, we want to use the push and pop methods to wrap all the following code in it to ensure that the code returns to the starting state whenever the for loop is run.

for(var i = 0; i <data.length; i++){
        translate(50,0);
        push()
            // code that draws  
        pop()
    }
Enter fullscreen mode Exit fullscreen mode

Then, declare a variable that accesses each object in the data array. For now, we will name the variable d. You can try printing "d" to see if it prints out everything in the JSON file. Then comment it out because won't be needing it.

for(var i = 0; i <data.length; i++){
        translate(50,0);
        push()
            let d = data[i]
            print(d);
        pop()
    }
Enter fullscreen mode Exit fullscreen mode

Now, it's time to draw the bars! We will be using rect() to draw the shape. The first two parameters are the location x and y. The last two are the width and length. We want to multiply the first parameter by 50 to give space between the bars. For the last parameter, which is the height, we want to access the value of the 本業薪資 property in the objects to give us the number s on the annual income of every job category. Then you want to multiply the height by some really small decimal number ( in my case, I used 0.0008 cuz it fits with the canvas perfectly) to adjust the ratio of the heights.

rect(i*50, 0, 50, d.本業薪資*0.0008); 
Enter fullscreen mode Exit fullscreen mode

You can add colors to the background by writing this on top of the rect() inside of the push/pop methods. I used a pink color and then added white strokes.

stroke(255);
fill(235, 131, 154);
Enter fullscreen mode Exit fullscreen mode

Drawing the texts
Now it's time to print the job category (行業) and income (本業薪資) on to the bars! We will first translate the text to the same starting point as the bars and rotate them by 90 degrees. Then, you can print the texts by again again accessing the values of the properties you want to use. The second and third parameters are locations on the x and y axis. I just played around with the numbers to make sure they show up centered on top of the bars.

translate(i*50, 0);
rotate(radians(90));
text(d.行業,10,-20)
text(d.本業薪資,175,-20)
Enter fullscreen mode Exit fullscreen mode

Make sure to add color to the text and take off the stroke!Make sure to add color to the text and take off the stroke!

function easeOutQuart(x){
return 1 - pow(1 - x, 4);
}
Enter fullscreen mode Exit fullscreen mode

And put this outside of the for loop inside of draw()

let animationProgress = easeOutQuart(map(frameCount, 0, 300, 0, 1, true))
Enter fullscreen mode Exit fullscreen mode

And times the height inside of rect() by animationProgress

rect(i*50, 0, 50, d.本業薪資*0.0008*animationProgress);
Enter fullscreen mode Exit fullscreen mode

You're done!
Woo you're now done! Now, every time you refresh you can see the the bar graph grow with the animation!

You can see the full interactive graph here and the code as well https://openprocessing.org/sketch/1152792

Top comments (0)