Built with blockbuilder.org
forked from GitNoise's block: multiline with threshold
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body {
margin:auto;
padding: 25px;}
.data path {
stroke: black;
stroke-width: 1.5px;
fill-opacity: 0.1;
}
</style>
</head>
<body>
<svg id="chart" width="600" height="300"></svg>
<script>
d3.csv("2020W3.csv").then(d => chart(d))
const chart = data => {
const threshold = 11;
const margin = {top: 15, right: 35, bottom: 15, left: 50};
const keys = data.columns.slice(1);
const result = data
.filter(d => d[data.columns[0]].indexOf('Adults') > -1)
.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.area()
.y0(yScale.range()[0])
.y1(d => yScale(d.value))
.x(d => xScale(d.year));
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('fill', 'url(#threshold)')
)
drawThreshold(svg, yScale, xScale, height, threshold);
}
const drawThreshold = (svg, yScale, xScale, height, threshold) => {
const group = svg.append('g').classed('threshold', true);
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