D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
GitNoise
Full window
Github gist
multiline with threshold
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:auto; padding: 25px;} .data path { fill: none; } .threshold line { stroke: black; stroke-dasharray: 2%; } .threshold rect { fill: red; fill-opacity: 0.05 } </style> </head> <body> <svg id="chart" width="500" height="410"></svg> <script> d3.csv("2020W3.csv").then(d => chart(d)) const chart = data => { const threshold = 12; const margin = {top: 15, right: 35, bottom: 15, left: 50}; const keys = data.columns.slice(1); const result = data.map( d => ({ id: d[data.columns[0]], values: keys.map(key => ({year: key, value: +d[key]})) })); const extent = { min: +d3.min(result, row => d3.min(row.values, v => v.value)), max: +d3.max(result, row => d3.max(row.values, v => v.value)), } const svg = d3.select("#chart"), width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom; const xScale = d3.scalePoint() .range([margin.left, width - margin.right]) .domain(keys); const yScale = d3.scaleLinear() .range([height - margin.bottom, margin.top]) .domain([0, extent.max]) var line = d3.line() .x(d => xScale(d.year)) .y(d => yScale(d.value)); svg.append("g") .classed("axis", true) .attr("transform", "translate(0," + (height - margin.bottom) + ")") .call(d3.axisBottom(xScale)); svg.append("g") .classed("axis", true) .attr("transform", "translate(" + margin.left + ",0)") .call(d3.axisLeft(yScale)); svg.append('g') .classed("data", true) .selectAll("path") .data(result) .join(enter => enter.append('path') .attr("d", d => line(d.values)) .style('stroke', 'url(#threshold)') ) drawThreshold(svg, yScale, xScale, height, threshold); } const drawThreshold = (svg, yScale, xScale, height, threshold) => { const group = svg.append('g').classed('threshold', true); group.append('line') .attr('x1', xScale.range()[0]) .attr('x2', xScale.range()[1]) .attr('y1', yScale(threshold)) .attr('y2', yScale(threshold)) group .append('rect') .attr('width', xScale.range()[1] - xScale.range()[0]) .attr('height', yScale.range()[0] - yScale(threshold)) .attr('x', xScale.range()[0]) .attr('y', yScale(threshold)) svg.append('defs').append("linearGradient") .attr("id", 'threshold') .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 0) .attr("y1", 0) .attr("x2", 0) .attr("y2", height) .selectAll("stop") .data([ {offset: 0, color: "blue"}, {offset: yScale(threshold) / height, color: "blue"}, {offset: yScale(threshold) / height, color: "red"}, {offset: 1, color: "red"} ]) .join("stop") .attr("offset", d => d.offset) .attr("stop-color", d => d.color); } </script> </body>
https://d3js.org/d3.v5.min.js