Data Visualisation with D3 journal Part: 3

Salman khalid
2 min readJun 21, 2018

Visualise Data with a Scatterplot Graph

A scatter plot is used to display a set of Data with respect to two variables. If the data is colour coded then one additional variable can be displayed. In second project, it is required to draw a scatter plot to display different cyclists time in minutes over the range of years. Here we have one additional information to display i.e cyclists with doping allegation and those who were not charged with anything.

In this article I would skip all the points which I have already mentioned in my previous article and they are again being used here. First I created an ajax request similar to the last project and then created svg instance. x-axis is quite similar but only difference is on the y-axis.

  1. Create Time Scale on y-axis

So far, we have been creating ‘linear scale’ but for y-axis we will use ‘time scale’ which can be created using time d3.timeParse method. Here is the code.

var timeParse = d3.timeParse("%M:%S");
var timeArray = [];
dataSet.forEach(function(value) {
timeArray.push(timeParse(value.Time));
});
const minTime = d3.min(timeArray, function(d) {
return d;
});
const maxTime = d3.max(timeArray, function(d) {
return d;
});
const yScale = d3
.scaleTime()
.domain([minTime, maxTime])
.range([padding, h - padding]);

Here we are first creating ‘timeArray’ while iterating over current dataSet. In the next step we are calculating min and max Time which are required to define scale. You might have noticed a small difference in range from the previous project. Actually, we want our y scale to show small values on top so cyclist with less time taken would be displayed on top.

2. Create Scatterplot with ‘Circle’ shape

In last project, we used ‘rect’ shape to create bar graph which cannot be used to scatter plot which needs dots. So here instead of rectangle shape we will go for ‘circle’. It requires three params to draw a circle at any point which are ‘x’ , ‘y’ and ‘radius’. Please have a look at the code first which I will explain next:

// Adding scatter plot data to axissvg
.selectAll("circle")
.data(dataSet)
.enter()
.append("circle")
.attr("class", "dot")
.attr("cx", d => xScale(d.Year))
.attr("cy", function(d) {
return yScale(timeParse(d.Time));
})
.attr("r", d => 8)
.attr("data-xvalue", d => d.Year)
.attr("data-yvalue", d => {
return timeParse(d.Time);
})
.style("fill", function(d) {
return d.Doping == "" ? "navy" : "red";
})

Time Scale behaves in a similar way like Linear Scale in terms of mapping time values to y-axis. For radius we are using a fixed value of 8 and color of a circle is being decided on the basis of its doping result. If it has doping information then its being filled as ‘red’ otherwise ‘navy’.

Here is the final look of my project in Code Pen.

I am currently working on rest of the projects required to complete this certification. You can track my progress here.

--

--