/* global d3 */ // D3 convention: define margin as an object called margin with these props: let margin = { top: 10, right: 20, bottom: 30, left: 30 }; let width = 400 - margin.left - margin.right; let height = 600 - margin.top - margin.bottom; const fullWidth = width + margin.left + margin.right; const fullHeight = height + margin.top + margin.bottom; let svg = d3.select('.chart') .append('svg') // Match the size of the chart-containing
with the viewport. .attr('width', fullWidth) .attr('height', fullHeight) // Beware the camelCase attribute name. // Graphics are : // 1. first drawn to full size, // 2. then cropped to viewBox // 3. then scaled to viewport. .attr('viewBox', `0 0 ${fullWidth} ${fullHeight}`) .append('g') .attr('transform', () => `translate(${margin.left},${margin.top})`); // Everything below this line no longer needs to care about margins. // At this point, the "svg" variable actually contains the selection. svg.append('rect') .attr('width', width) .attr('height', height) .style('fill', 'lightblue') .style('stroke', 'green'); let yScale = d3.scaleLinear() .domain([0, 100]) // reversed because SVG coordinates are top to bottom. .range([height, 0]); let yAxis = d3.axisLeft(yScale); // For 2nd ticks() param: // - '%' assumes a [0,1] domain // - 's' uses human-readable sizes // - '.2s' gives 2 digits after decimal separator // The value is a suggestion, in this case we get 6, not 5. // .ticks(5); // Can use explicit tick positions: // .tickValues([8, 19, 43, 77]) svg.call(yAxis); let xScale = d3.scaleTime() .domain([new Date(2016, 0, 1, 6), new Date(2016, 0, 1, 9)]) .range([0, width]); let xAxis = d3.axisBottom(xScale) .ticks(5) // .tickSize(20) .tickSizeInner(10) .tickSizeOuter(20) .tickPadding(15) // Not every 45 minutes, but every 45 minutes after the hour, plus the hour. //.ticks(d3.timeMinute.every(45)) ; // This would appear at the top (but drawn for a bottom position, ticks down). // svg.call(xAxis); // So we put it in an additional below the graph. svg.append('g') .attr('transform', `translate(0, ${height})`) .call(xAxis);