Public
Edited
Jun 21, 2023
1 star
Insert cell
Insert cell
{
const height = 200;
const svg = d3.select(DOM.svg(width, height))
.style('border', '1px solid black');

svg.selectAll('rect')
.data(anomalyValues)
.join('rect')
.attr('x', (d, i) => width * i / anomalyValues.length)
.attr('y', 0)
.attr('width', (d, i) => width / anomalyValues.length)
.attr('height', height)
.style('fill', d => scaleAnomalyPuOr(d))
return svg.node();
}
Insert cell
Insert cell
dataset = FileAttachment("HadCRUT5_global_annual.csv").csv({typed: true})
Insert cell
dataset
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
anomalyValues = dataset.map(d => d['Anomaly (deg C)'])
Insert cell
anomalyRange = d3.extent(anomalyValues)
Insert cell
Insert cell
scaleAnomalyPuOr = d3.scaleDiverging(t => d3.interpolateRdBu(1 - t))
.domain([anomalyRange[0], 0, anomalyRange[1]])
Insert cell
drawGradient(scaleAnomalyPuOr, anomalyRange[0], anomalyRange[1], anomalyValues.length)
Insert cell
Insert cell
function* drawGradient(colors, min = 0, max = 1, n = 256) {
// Create a new canvas with it's width set to the number of colors and it's height to one.
const ctx = DOM.context2d(n, 1, 1);
// Adjust the styling of the canvas to it is displayed larger.
ctx.canvas.style.width = "100%";
ctx.canvas.style.height = "40px";
ctx.canvas.style.imageRendering = "pixelated";
// Fill the canvas's pixels based on the given color function.
for (let i = 0; i < n; ++i) {
// For each color draw a colored rectangle in the size of a pixel.
ctx.fillStyle = colors(min + (max - min) * i / (n - 1));
console.log(min + (max - min) * i / (n - 1));
ctx.fillRect(i, 0, 1, 1);
}

// Return the canvas.
yield ctx.canvas;
}
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