Building Box Plots Using JavaScript: Visualizing World Happiness | by Wayde Herman | Towards Data Science

Data visualization is an important and sometimes undervalued tool in a data scientist’s toolkit. It allows us to gain an understanding and intuition about the data, through exploratory data analysis, which influences preprocessing, feature engineering, and the correct machine learning algorithm choice. It also helps to better evaluate models and even allows you to spot areas in the data where models could have poor performance.
Taking data visualization one step further by adding interactivity is even more advantageous. By adding interactive elements to your visualizations you create a more engaging experience. This in turn makes a user ‘explore’ visualizations instead of just reading them!
In this tutorial, I will be covering how to build an interactive data visualization, specifically a box plot as an example, using JavaScript and a charting library. I will begin by first briefly covering the basics of box plots before going through the steps of building one and then finally using the technique in a fun example to investigate the distribution of happiness between the different regions of the planet in an attempt to answer the question: ‘Where should you live to be happier?’.
A box plot, also widely called a box-and-whisker plot, is a data visualization technique used to visualize descriptive statistics of datasets. While this chart type is not as useful as a histogram at understanding a single datasets distribution, these visualizations do well at allowing a user to compare different datasets.
Box plots visualize the following summary statistics: The median, the first and third quartile (Q1 and Q3), the low and the high as well as the outliers. These are displayed as follows:
To build an interactive data visualization there are a quite a few options. If you want to learn about JavaScript alternatives, you can have a look here. In this example I will be using a JS charting library and specifically AnyChart. I’m going with AnyChart as it supports box-and-whisker plots (among multiple other chart types), and I think both its documentation and API are really great for beginners and advanced users alike but alternatives which better suit your needs can work too and will follow similar steps.
The first step is to set up a page for the box plot visualization. This includes adding the HTML elements, loading the required scripts and setting up the CSS for our chart. Which looks like:
<html>  <head>    <script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script>    <style type="text/css">      html, body, #container {        width: 100%;        height: 100%;        margin: 0;        padding: 0;      }     </style>  </head>  <body>    <div id="container"></div>  </body>  <script>    anychart.onDocumentReady(function () {      // code goes here.    });  </script></html>
When using a charting library you will need to import the correct script in order to use that library and in some cases different modules for different chart types. For access to AnyChart’s box-and-whisker chart, for example, I will need to use the base module.
Once that is sorted I will then need to set the CSS properties for my chart element. Here I have set the box chart to have a width and height of 100%. You can change this depending on your own use case. CSS width and height properties accept percentages (of the parent element), and various length units (most commonly pixels).
Finally, I have a script tag with the JavaScript function anychart.onDocumentReady() which is simply a function triggered when the document is loaded. Placing the JavaScript charting code within this function ensures that the code does not trigger before the page is ready which can lead to bad results (read up on asynchronous JavaScript to learn more about this).
I will be using data sourced from the World Happiness Report which is the results compiled from a global survey that attempts to quantify happiness of each country’s citizens to a value between 0 and 10. I obtained this data from Kaggle, a great place to find fun and interesting datasets. Admittedly most of them are geared towards machine learning applications but a few work well for data visualization purposes.
In preparation for drawing box plots, I need to provide the data in a format and form that is accepted by our chosen charting library. For example, AnyChart JS accepts box plot data in the following form:
{x:"Name", low: value, q1: value, median: value, q3: value, high: value, outliers: array}
Where x is the label, q1 and q3 are the first and third quartile values, low and high are the 1.5 x the interquartile range below q1 and 1.5 x the interquartile range above q3 respectively, and the outliers is an array containing all the outlier values.
I have conveniently preprocessed the data from the world happiness report to produce the following array:
var data = [  {x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53},  {x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40},  {x:"Australia and New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33},  {x:"Middle East and Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27},  {x:"Latin America and Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]},  {x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74},  {x:"Central and Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60},  {x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38},  {x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]},  {x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}]
With only these few lines of code I can draw my box plots:
// create a chartchart = anychart.box();// create a box series and set the dataseries = chart.box(data);// set the container idchart.container("container");// initiate drawing the chartchart.draw();
And putting this all together, you will get the following:
<html>  <head>    <script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script>    <style type="text/css">      html, body, #container {        width: 100%;        height: 100%;        margin: 0;        padding: 0;      }    </style>  </head>  <body>    <div id="container"></div>  </body>  <script>    anychart.onDocumentReady(function () {      var data = [        {x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53},        {x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40},        {x:"Australia and New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33},        {x:"Middle East and Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27},        {x:"Latin America and Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]},        {x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74},        {x:"Central and Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60},        {x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38},        {x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]},        {x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}      ]      // create a chart      chart = anychart.box();      // create a box series and set the data      series = chart.box(data);      // set the container id      chart.container("container");      // initiate drawing the chart      chart.draw();    });  </script></html>
Which results in:


HTML




CSS




JS




Result



Skip Results Iframe

<html>
    <head>
        <script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

html, body, #container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
anychart.onDocumentReady(function () {
  var data = [
    {x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53},
    {x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40},
    {x:"Australia & New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33},
    {x:"Middle East & Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27},
    {x:"Latin America & Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]},
    {x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74},
    {x:"Central & Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60},
    {x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38},
    {x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]},
    {x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}
            ]

  // create a chart
  chart = anychart.box();

  // create a box series and set the data
  series = chart.box(data);

  // set the container id
  chart.container("container");

  // initiate drawing the chart
  chart.draw();

  });

This Pen is owned by Wayde Herman on CodePen.



See more by @waydeherman on CodePen



This Pen doesn't use any external CSS resources.


This Pen doesn't use any external JavaScript resources.