d3 wannabee

by basickarl

HTML

<script src="https://d3js.org/d3.v4.js"></script>
<div id="line-graph"></div>

CSS

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.dot {
  fill: lightblue;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.axis {
  fill: black;
  font-family: Times New Roman;
  font-size: 24px;
}

.axis line {
  stroke: lightgrey;
}

.axis text {
  fill: lightblue;
}

JavaScript

'use strict';

const data = d3.range(40).map((i) => {
    if (i % 5) {
        return {
            x: (i / 39),
            y: ((Math.sin(i / 3) + 2) / 4)
        };
    }
    return null;
});

const margin = { 
    top: 40, 
    right: 40, 
    bottom: 40, 
    left: 60 
};
const width = (960 - margin.left - margin.right);
const height = (500 - margin.top - margin.bottom);

const x = d3.scaleLinear().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);

const line = d3.line()
    .defined(d => d)
    .x(d => x(d.x))
    .y(d => y(d.y));

const svg = d3.select('#line-graph')
    .append('svg:svg')
    .datum(data)
    .attr('width', (width + margin.left + margin.right))
    .attr('height', (height + margin.top + margin.bottom))
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

// X-Axis
const xAxis = d3.axisBottom(x)
    .ticks(9) // How many gridlines
    .tickSizeInner(-height) // Ticks in between the outer ticks
    .tickSizeOuter(0) // Ticks on both outer sides
    .tickFormat(''); // Removes tick labels
// Custom X-Axis function
function customXAxis(g) {
    g.call(xAxis);
}
// Add X-Axis
svg.append('g')	
    .attr('class', 'axis') // CSS class
    .attr('transform', 'translate(0,' + height + ')')
    .call(customXAxis);
    
// Y-Axis
const yAxis = d3.axisLeft(y)
    .ticks(9) // How many gridlines
    .tickSizeInner(10) // Ticks in between the outer ticks
    .tickSizeOuter(0) // Ticks on both outer sides
    .tickPadding(10); // Spacing between ticks and labels
// Custom Y-Axis function
function customYAxis(g) {
    g.call(yAxis);
    g.select('.domain').remove(); // Removes the initial axis line
    g.select('.tick:nth-of-type(1)').attr('display', 'none');
    g.select('.tick:nth-of-type(2)').attr('display', 'none');
    g.select('.tick:nth-last-of-type(1)').attr('display', 'none');
    g.select('.tick:nth-last-of-type(2)').attr('display', 'none');
}
// Add Y-Axis
svg.append('g')	
   ...