Scatter Chart with Chart.js

Now when you’ve seen Highcharts in action, let’s get back to Chart.js and see how to build an interactive scatter chart. Remember that scatter charts (also scatterplots) are used to display data of 2 or more dimensions. Figure 12.5 shows the relationship between household income and test performance for school districts in Connecticut. Using x- and y-axes to show two dimensions, it is easy to see that test performance improves as household income goes up.

Figure 12.5: Interactive scatter chart with Chart.js. Explore the interactive version.

To create your own scatter plot with Chart.js, with data loaded from a CSV file, you can:

  1. Go to our GitHub repo that contains the code for the chart shown in Figure 12.5, log into your GitHub account, and click Use this template to create a copy that you can edit.

  2. Prepare your data in CSV format and upload into a data.csv file. The first two columns should contain x- and y-values respectively, and the third column should contain the point name that will appear on mouse hover.

| income | grades | district |
| 88438  | 1.7    | Andover  |
| 45505  | -0.4   | Ansonia  |
| 75127  | 0.5    | Ashford  |
| 115571 | 2.6    | Avon     |
  1. In script.js, customize the values of variables shown in the code snippet below:
var TITLE = 'Income and Test Scores in Connecticut School Districts, 2009-13';

var POINT_X = 'income'; // column name for x values in data.csv
var POINT_X_PREFIX = '$'; // prefix for x values, eg '$'
var POINT_X_POSTFIX = ''; // postfix for x values, eg '%'

var POINT_Y = 'grades'; // column name for y values in data.csv
var POINT_Y_PREFIX = ''; // prefix for x values, eg 'USD '
var POINT_Y_POSTFIX = ''; // postfix for x values, eg ' kg'

var POINT_NAME = 'district'; // point names that appear in tooltip
var POINT_COLOR = 'rgba(0,0,255,0.7)'; // eg `black` or `rgba(10,100,44,0.8)`
var POINT_RADIUS = 5; // radius of each data point

var X_AXIS = 'Median Household Income, USD'; // x-axis label, label in tooltip
var Y_AXIS = 'Grade, Relative to Average'; // y-axis label, label in tooltip

var SHOW_GRID = true; // `true` to show the grid, `false` to hide

A similarly good-looking interactive chart can be constructed in Highcharts, although it is up to you to undertake that challenge. In the meanwhile, remember to refer to the official Chart.js documentation if you want to further tweak your chart.

You may want to show an additional third variable, such as enrollment in each school district, in the same scatter chart. You can do so by resizing each dot so that larger school districts are marked with a larger circle, and smaller districts are shown using a smaller dot. Such use of size will result in a bubble chart, which we will look at next.