12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- /* global d3 */
- // D3 convention: define margin as an object called margin with these props:
- let margin = {
- top: 10,
- right: 20,
- bottom: 60,
- left: 40
- };
- let width = 425 - margin.left - margin.right;
- let height = 625 - margin.top - margin.bottom;
- let svg = d3.select('.chart')
- .append('svg')
- // Match the size of the chart-containing <div>.
- .attr('width', width + margin.left + margin.right)
- .attr('height', height + margin.top + margin.bottom)
- .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 <g> 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 <g> below the graph.
- svg.append('g')
- .attr('transform', `translate(0, ${height})`)
- .call(xAxis);
|