JS show it! Today: Interactive Choropleth World Map using Google GeoChart visualization

Mon, 05/14/2018 - 10:26 admin

JavaScript Nuggets on Demand

KNIME Analytics Platform is extremely flexible. It offers not only a number of pre-packaged functionalities for prototyping or routine work, but also a number of integrations for the free coding days. One of these integrations imports the power of JavaScript code into the platform.

This blog post series aims at providing nuggets of JavaScript code to implement more creative drawing and plots than what is already available with the pre-packaged nodes. The nuggets of JavaScript code proposed here implement only one functionality and are explained step by step for all, even the JavaScript beginners, to understand.

Today: Interactive Choropleth World Map using Google GeoChart visualization

Authors: Rosaria Silipo & Paolo Tamagnini

Figure 1. A choropleth map is a geographical map where areas are colored, shaded, or patterned according to a corresponding calculated measure, in this case logarithmic number of 2013 population on a world map.

The Plot

Today we want to draw the choropleth map as shown above. So what do we need?

  • A map of the countries of the world and the corresponding numbers of population.
  • A short JavaScript code to load the Google Charts library and draw the choropleth map based on the population numbers of each country.
  • A Generic JavaScript View node to execute such code within a KNIME workflow.

Our dataset is the CSV file population2013.csv and it contains a list of 214 world countries with their corresponding population numbers as of 2013.

We also have a generic JavaScript View node. The smallest workflow would simply include a File Reader node to read the CSV file and a Generic JavaScript View node with the right JavaScript code nugget to draw the choropleth map. So let’s now have a look at this nugget of JavaScript code.

The JavaScript Code Nugget

The JavaScript code nugget, which will draw a choropleth world map, consists of three parts, which do the following:

  • Import a dataset from the KNIME input data table object to be used with the Google libraries
  • Transform the dataset into a Google object, define a visualization.GeoChart object named “chart”, and draw the chart with the function chart.draw(). This part is encapsulated in the DrawChart() function, which is used as a callback function when loading the Google visualization module and its corechart package.
  • Load the Google JavaScript API via jQuery getScript() function

Below is the final JS code nugget to insert in the JavaScript editor of the Generic JavaScript View node’s configuration dialog.

// Loading the KNIME table onto var dataset
// Dataset holding table
var dataset = [];
// Push column headers
dataset.push(knimeDataTable.getColumnNames());
// Dataset holding a single row
var rowDataset = [];
// Iterate over table and fill dataset
var rows = knimeDataTable.getRows();
for (var rowID = 0; rowID < knimeDataTable.getNumRows(); rowID++) {
	var row = rows[rowID];
	rowDataset = [];
	for (var colID = 0; colID < knimeDataTable.getNumColumns(); colID++) {
		rowDataset.push(row.data[colID]);
	}
	dataset.push(rowDataset);
}

// Build drawChart()  function, the function that actually draws the map
// Create div holding the chart
$('body').append('<div id="chart_div"></div>');

// Create callback function which is called after the visualization module is loaded
drawChart = function() {

	// Convert dataset to Google visualization DataTable object
	var data = google.visualization.arrayToDataTable(dataset);

	// Define colors for lowest to highest value (here in shades of blue)
	var options = {colorAxis: {colors: ['#deebf7','#9ecae1','#3182bd']}};
	// Create chart with chart_div as parent
	var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));

	// This is the function that actually draws the chart. It takes the first 2 columns of dataset “data”.
	// 1st column is supposed to be country and 2nd column is supposed to be the coloring number.
	// “options” contains color heatmap to use.
	chart.draw(data, options);
}

// Load Google JavaScript API via jQuery getScript()
$.getScript('https://www.google.com/jsapi')

	// Load Google visualization module with drawChart() as callback function
	.done(function( script, textStatus ) {
		google.load('visualization', '1', {packages:['corechart'], callback:drawChart});
	})

	// Inform user about failure
	.fail(function( jqxhr, settings, exception ) {
		alert("Loading Google API failed.");
});

The function chart.draw() from the Google Charts library assumes that the first column in the data contains the country names and the second column the population numbers. When feeding the Generic JavaScript View node make sure that the column order in the dataset is correct.

Note. When you copy this code into the JavaScript editor in the configuration dialog of the Generic JavaScript View node, remember to check JQuery dependency, since the Google JavaScript API is loaded using the getScript() function of the jQuery library.


The getScript() method from jQuery is great to load a single JS library. However when more concurrent, possibly dependent, JS libraries are needed, other load methods might be more suitable. We will talk about those in another post. Stay tuned!

Also, note that we have defined a heat map going from light blue (least populated countries) to dark blue (most populated countries).

It is common practice to use a monochromatic color scale. We chose the scale from light blue to dark blue as recommended in the “Color Brewer 2.0” web site.

Figure 2. The JavaScript code nugget used to draw the choropleth in Figure 1 as inserted in the editor of the Generic JavaScript View node.

The KNIME Workflow

If we actually apply the above code in a Generic JavaScript View node directly to the data of the population2013.csv file, the map will be colored light blue with only 2 countries (India and China) in dark blue, due to their very large populations. This is because we are dealing with populations in absolute numbers.

In order to appreciate the differences in population a bit better, we could use a logarithmic scale. In this case a Math Formula node calculates log(2013) for each country to append to the original dataset.

After re-ordering the columns so as to have the log(2013) column at the second position from the left, we feed the Generic JavaScript View node containing the code above. This produces the choropleth map displayed in Figure 1.

Note. The Google Geocoding API is loaded lazily. An internet connection is required when opening the view of the Generic JavaScript View node. Also, the map will take a longer or shorter time to load depending on the speed of your internet connection.


Now it would be nice to add a title to the plot. However, I think we have done enough JavaScript for today. Let’s use a good old Text Output node and add the following tiny bit of HTML code:

<h1><font color="gray">Population in logarithmic numbers by world countries in 2013</font></h1>

Then let’s wrap both nodes – the Generic JavaScript View node and the Text Output node – into a wrapped metanode for a composite view. To make sure that the title comes on top of the page, open the metanode, select the button for the metanode layout in the tool bar, and set the position of the two nodes in a 2x1 matrix: Text Output node at (1,1) and Generic JavaScript View node at (2,1), as shown in Figure 3.

Figure 3. The basic layout of the composite view of a wrapped metanode, containing a Text Output node for the title and a Generic JavaScript View node for the choropleth map. The title is placed at the top of the view and the choropleth map underneath.

Indeed, now, if we right-click the metanode and select its “Interactive Vew” item, we can see the same choropleth map with a gray title, exactly as in Figure 1. Also, if we execute the workflow from a KNIME WebPortal, the final web page will also contain this interactive view with choropleth and title.

We can also go one step further and combine the two plots: the one plot with pure numbers and the other with logarithmic numbers, and display them side by side, each with its own title, in the same view. This is achieved in the last wrapped metanode, which contains two Generic JavaScript View nodes and two Text Output nodes, placed on a 2x2 layout grid. The final composite view is shown in Figure 4.

Again if running on a KNIME WebPortal, this composite view translates into a web page with multiple choropleths and titles.

The final workflow is shown in Figure 5 and is also available on the EXAMPLES server under 03_Visualization/04_Geolocation/07_Choropleth_World_Map03_Visualization/04_Geolocation/07_Choropleth_World_Map* .

Figure 4. Composite view with two choropleth maps, side by side. On the left is the choropleth map based on pure numbers; on the right, it is based on logarithmic numbers. You might convene that the logarithmic scale allows for better appreciation of the difference in population numbers.


Figure 5. The workflow used to draw all those choropleths. From top to bottom, the workflow produces choropleth maps based on pure population numbers, on logarithmic population numbers, with a title, and shown side by side. This workflow is available on the KNIME EXAMPLES server under 03_Visualization/04_Geolocation/07_Choropleth_World_Map03_Visualization/04_Geolocation/07_Choropleth_World_Map* .

Summary and Next Steps

Today we drew a choropleth map of the world showing population numbers. To do this we used a short JavaScript code nugget to load the Google Charts library and color code the world map areas according to the input numbers and countries. As a bonus, we also showed how to add a title and/or another world map choropleth in the composite view of a wrapped metanode.

The workflow is available on the EXAMPLES server under 03_Visualization/04_Geolocation/07_Choropleth_World_Map03_Visualization/04_Geolocation/07_Choropleth_World_Map* .

If you enjoyed this, please share it generously and let us know your ideas for future JavaScript based visualizations at willtheyblend@knime.com