Published
Edited
Nov 29, 2020
Insert cell
md`# Line Chart Demo`
Insert cell
width = 800
Insert cell
height = 800
Insert cell
margin = 50
Insert cell
simulationSteps = 50
Insert cell
passengerCount = 25
Insert cell
lineGen = {
return d3
.line()
.x((d, i) => xScale(i))
.y((d, i) => yScale(d.avg));
}
Insert cell
xScale = {
return d3.scaleLinear()
.domain([0, simulationSteps])
.range([margin, width - margin]);
}
Insert cell
yScale = {
return d3
.scaleLinear()
.domain([100, 0])
.range([margin, width - margin]);
}
Insert cell
{
let svg = d3
.create('svg')
.attr("width", width)
.attr('height', height)
.attr('id', 'mainViz');

let bg = svg
.append('rect')
.attr("width", width)
.attr('height', height)
.attr('fill', '#222');

svg
.append('path')
.attr('d', drawingDataString)
.attr('fill', 'white')
.attr('transform', 'rotate(-30 50 50) translate(200 200) scale(2 2)').attr('id','shape');

svg
.datum(animatedData)
.append('path')
.attr('d', lineGen)
.attr('id', 'avgPath')
.attr('stroke', '#fff')
.attr('fill', 'none');

return svg.node();
}
Insert cell
animatedData = []
Insert cell
addDataPoint = function() {
let newData = Math.random();
animatedData.push({ avg: newData * 10 + 50 });

if (animatedData.length > simulationSteps) {
animatedData.shift();
}

d3.select('#avgPath')
.datum(animatedData)
.attr('d', lineGen)
.attr('stroke', d3.interpolateViridis(newData));

d3.select('#shape').attr('fill', d3.interpolateViridis(newData));
}
Insert cell
{
let timeOut = 0;
while (timeOut < simulationSteps) {
yield Promises.delay(100, addDataPoint());
}
}
Insert cell
data = {
let data = [];

for (let i = 0; i < simulationSteps; i++) {
// data.push({
// avg: Math.random() * 100,
// min: Math.random() * 100,
// max: Math.random() * 100
// });

let tickData = [];
for (let j = 0; j < passengerCount; j++) {
tickData.push(Math.random() * 100);
}
data.push(tickData);
}

return data;
}
Insert cell
dataProcessed = {
let synthesizedData = [];

for (let i = 0; i < simulationSteps; i++) {
let tick = data[i];

let tickData = {
max: d3.max(tick, d => d),
min: d3.min(tick, d => d),
avg: d3.mean(tick, d => d)
};

synthesizedData.push(tickData);
}

return synthesizedData;
}
Insert cell
drawingDataString = {
return "M1.21,27.58c0,0,2.1-21.46,18.4-8.07s-47.6,40.5,0.81,38.08c48.41-2.42,6.62,1.61,25.66-18.4 S79.63,5.31,74.63,40c-5,34.69,10.49,59.19,21.95,36.05S75.6,103.1,52.6,75.18S18.15,33.22,38.48,25.64s4.84-26.63-2.9-14.68 S-1.38,56.95,1.21,27.58z";
}
Insert cell
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