This example was motivated by two blog entries posted by Lisa Charlotte Rost on her blog. It shows the tight relationship between a country's average personal income and the average life expectancy. The point areas are proportional to the country's population. Left click on a point to see the country name. Drag the plot area with the mouse to pan in any direction. Zoom in and out with the mouse central button.
var sketch = function(p) {
// Global variables
var table = undefined;
var plot = undefined;
// Load the table before the sketch is run
p.preload = function() {
// Load the cvs dataset.
// The file has the following format:
// country,income,health,population
// Central African Republic,599,53.8,4900274
// ...
table = p.loadTable("https://raw.githubusercontent.com/jagracar/grafica/master/examples/LifeExpectancy/data/data.csv", "header");
};
// Initial setup
p.setup = function() {
var points, pointSizes, row, data, country, income, health, population, scaleFactor;
// Create the canvas
p.createCanvas(750, 450);
// Save the data in an array and calculate the point sizes
points = [];
pointSizes = [];
for (row = 0; row < table.getRowCount(); row++) {
data = table.getRow(row);
// Check that the row contains valid data
if (data.get("country") !== "undefined") {
country = data.getString("country");
income = data.getNum("income");
health = data.getNum("health");
population = data.getNum("population");
points[row] = new GPoint(income, health, country);
// The point area should be proportional to the country population
// population = pi * sq(diameter/2)
scaleFactor = p.width / 750;
pointSizes[row] = 2 * Math.sqrt(population / (200000 * Math.PI)) * scaleFactor;
}
}
// Create the plot
plot = new GPlot(this);
plot.setOuterDim(p.width, p.height);
plot.setTitleText("Life expectancy connection to average income");
plot.getXAxis().setAxisLabelText("Personal income ($/year)");
plot.getYAxis().setAxisLabelText("Life expectancy (years)");
plot.setLogScale("x");
plot.setPoints(points);
plot.setPointSizes(pointSizes);
plot.activatePointLabels();
plot.activatePanning();
plot.activateZooming(1.1, p.CENTER, p.CENTER);
};
// Execute the sketch
p.draw = function()...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.