Scatterplot Graph is a D3.js Version 5 application.
This project is from FreeCodeCamp Project 2
Source Code
When some of the data is Minutes:Seconds, formatting is needed to be able to convert the data to a number of pixels. Suppose “37:45” is 37 minutes and 45 seconds, this is not a number of pixels. I need the number of pixels to know where on the Y Axis the data goes.
This code to do this is:
var specifier = "%M:%S";
var parserMS = d3.timeParse(specifier);
var parsedData = dataset.map(function(d){
return parserMS(d['Time']);
});
var yAxis = d3.axisLeft(yScale).tickFormat(d3.timeFormat("%M:%S"));
.attr("cy", function(d, i){
return yScale(parsedData[i]) - 10;
})
The Y Axis label was tricky because I did not know that SVG translate() moves 3 things: the text, the axis, and the origin.
The code is:
D3 elements are created in an SVG element, which has an origin anchored at the top left at 0,0. When a transform attribute is applied a text element on the SVG canvas, a new current coordinate system is established on that transformed text element along with a new origin.
.attr(“transform”, “translate(30, 300) rotate(-90)”)
This moves the text to a new coordinate system where the text is anchored at 0,0 (which is 30,300 on the containing svg’s coordinate system.
The order of values in range() determines if the Y Axis is upside down or not.
.range([50, height - 50]);
, 39:45 is at the bottom and 37:00 is at the top
.range([height - 50, 50]);
, 37:00 is at the bottom and 39:45 is at the top