Screen Shot 2015-05-23 at 1.32.56 PM

See the live map here.

Jqvmap is an excellent JavaScript library for making sleek D3-style interactive vector maps quickly and easily. However, its suggested technique for visualizing data (see the library’s documentation) leaves something to be desired.

This post suggests another way, using Geostats, another excellent JS library.

To be clear: jqvmap’s dataviz technique works, but it’s not appropriate for ever kind of data. It first finds the maximum and minimum values, then does some complicated math to split the range into different colour classes and assign hex colour codes to each feature.

If your data has a big range, with most countries clustered around one end and a few outliers in the other, the colours won’t look good.

Enter geostats

Geostats is a JS library that does math on your data so you don’t have to. It calculates all sorts of stats (like max and min) and splits your data into intervals for effective colouring.

People familiar with GIS will recognize these intervals: Jenks breaks, equal intervals, quintiles, etc. Switching between them is easy, so you can experiment with different colour classifications.

For this example, we’ll use jqvmap’s world map and data from the UN Office on Drugs and Crime on people treated for drug abuse (Treatment demand, under “Drug use”). The data has been converted to JSON using Shan Carter’s handy Mr. Data Converter tool, and normalized by population using World Bank data.

The data should look like this, with the jqvmap country codes as keys:

 

First, load jQuery, Jqvmap and Geostats. I used an updated map made by GitHub user steelcrashed that includes new countries like South Sudan and Macedonia.

 

Create an array of colours. I use ColorBrewer for palette suggestions.

 

You need to feed Geostats your data as an array. I do this by iterating through the JSON and filling the array.

 

Create a Geostats objects and feed it your data. Choose with classification method you want and the number of intervals. In this case, I chose Jenks breaks on six intervals.

 

Here’s what the intervals look like:

 

Now we loop through our data and assign colours to the Jqvmap colors object. Null values were assigned a 0 in my data, so they get a grey colour for no data.

 

Now initiate your map, add whatever parameters you want, and the ‘colors’ object as the colors, and voila.

 

The full, functional map can be found here.

 

Leave a Reply

Your email address will not be published. Required fields are marked *