Published
Edited
Feb 23, 2018
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3-fetch@1")
Insert cell
Insert cell
airData = d3.json("https://api.carbonintensity.org.uk/intensity")
Insert cell
Insert cell
airData.data
Insert cell
Insert cell
airData.data[ 0 ]
Insert cell
Insert cell
airData.data[ 0 ].intensity
Insert cell
Insert cell
daysOfAirData = d3.json("https://api.carbonintensity.org.uk/intensity/2018-02-10/2018-02-17")
Insert cell
Insert cell
Insert cell
{
// Creates a drawing context for us. It's relative magic. The size of the drawing area is given by "width", which holds the width of the window, and "500", which is 500 high.
const context = DOM.context2d(width,500);
// We are drawing a line graph - so we want what is called a "path". This starts the path.
context.beginPath()
// With the drawing pen "up", we move to this point - x-value is 0 (the left edge of the drawing area), and the second value is the first intensity value used as the y-value. I'll explain why it's "500 - ..." below.
context.moveTo(0,500 - daysOfAirData.data[0].intensity.forecast)
// Now we create the line graph using all the points.
// We're using a for loop, to scan over all 337 data points we retrieved...
// remember: x goes from 0 to 337, going up by one each time
// "lineTo" now draws from the previous position to the one specified
for( let x = 0; x < 337; x++ ) context.lineTo( x*2, 500 - daysOfAirData.data[x].intensity.forecast )
// This sets the kind of line we want to be drawn - in this case, coloured blue.
context.strokeStyle = "blue"
// This actually draws the line we've created on the canvas
context.stroke()
// and it's the canvas that is the result of the cell, getting displayed below.
return context.canvas
}
Insert cell
Insert cell
{
const context = DOM.context2d(width,500);

context.beginPath()
context.moveTo(0,daysOfAirData.data[0].intensity.forecast)
for( let x = 0; x < 337; x++ ) context.lineTo( x*2, daysOfAirData.data[x].intensity.forecast )
context.strokeStyle = "blue"
context.stroke()
return context.canvas
}
Insert cell
Insert cell
Insert cell
width
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