Published
Edited
Nov 28, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
channelID = 1587045
Insert cell
Insert cell
rawData = {
//for making sure we get data quickly after page load
let firstRun = true;

//infinite loop
while (true) {
//visit API and parse as JSON
const data = await d3.json(
"https://api.thingspeak.com/channels/" +
channelID +
"/feeds.json?results=" +
sampleCount
);

//check if the page just loaded
if ((firstRun = true)) {
//make sure we wait on future requests
firstRun = false;
yield data.feeds;
} else {
//wait 15 seconds then request again
yield Promises.delay(15000, data.feeds);
}
}
}
Insert cell
Insert cell
Insert cell
timeStamps = rawData.map((d) => new Date(d.created_at))
Insert cell
Insert cell
cleanedData = rawData.map((feed) =>
Object.entries(feed)
.filter((d) => d[0].includes("field"))
.map((d, i) => ({ label: d[0], value: d[1], height: i }))
)
Insert cell
Insert cell
xScale = d3
.scaleLinear()
.domain([0, 255])
.range([margin, svgWidth - margin])
Insert cell
yScale = d3
.scaleLinear()
.domain([0, cleanedData[0].length - 1])
.range([svgHeight - margin, margin])
Insert cell
lineGen = d3
.line()
.x((d) => xScale(parseInt(d.value)))
.y((d) => yScale(d.height))
.curve(d3.curveCatmullRom)
Insert cell
Insert cell
svgWidth = 200
Insert cell
svgHeight = 400
Insert cell
margin = 40
Insert cell
Insert cell
{
const svg = d3
.create("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);

svg
.append("rect")
.attr("width", svgWidth)
.attr("height", svgHeight)
.attr("fill", d3.interpolateViridis(0));

svg
.selectAll(".curves")
.data(cleanedData)
.enter()
.append("path")
.attr("fill", "none")
.attr("stroke", (d, i) => d3.interpolateViridis(i / (sampleCount - 1)))
.attr("stroke-width", 2)
.attr("opacity", 0.5)
.attr("class", "curves")
.attr("d", (d) => lineGen(d));

return svg.node();
}
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