Published
Edited
Jan 11, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
// ===== INPUT =====
const w = 100;
const h = w;
const containerId = '#line-chart-container';
// =================
const draw = (colors, data) => {
const points = data.map((d, i) => [i, d]);
const fgcolor = colors[0];
const bgcolor = colors[1];
const xScale = d3
.scaleLinear()
.domain([0, points.length - 1])
.range([0, w]);
const svg = d3
.select(containerId)
.attr('viewBox', [0, 0, w, h])
.attr('height', 500)
.attr('width', 500);
const area = d3 // area with gradient & no stroke
.area()
.x(d => xScale(d[0]))
.y1(d => h - d[1])
.y0(h);
const line = d3 // line with stroke
.line()
.x(d => xScale(d[0]))
.y(d => h - d[1]);

svg.attr('viewBox', [0, 0, w, h]);
svg.selectAll('*').remove();
svg // append the background
.append('rect')
.attr('width', '100%')
.attr('height', '100%')
.attr('fill', bgcolor);
svg // append the area
.append('path')
.attr('d', area(points))
.attr('stroke', 'none')
.attr('fill', 'url(#gradient)');
svg // append the line
.append('path')
.attr('d', line(points))
.attr('stroke', fgcolor)
.attr('fill', 'none');

// ===== GRADIENT DEFINITION =====
var defs = svg.append('defs');
var gradient = defs
.append('linearGradient')
.attr('id', 'gradient')
.attr('x1', '50%')
.attr('x2', '50%')
.attr('y1', '0%')
.attr('y2', '100%');
gradient
.append('stop')
.attr('class', 'start')
.attr('offset', '0%')
.attr('stop-color', fgcolor)
.attr('stop-opacity', 1);
gradient
.append('stop')
.attr('class', 'end')
.attr('offset', '100%')
.attr('stop-color', bgcolor)
.attr('stop-opacity', 1);
// ===============================
};

draw(['#7fddaf', '#5fce88'], values);
// let count = 0;
// while (count < 100) {
// if (count % 2 == 0) {
// draw(['#7fddaf', '#5fce88'], d3.shuffle(values));
// } else {
// draw(['#f08b97', '#ec5564'], d3.shuffle(values));
// }
// await new Promise(r => setTimeout(r, 2000));
// count++;
// }
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more