Published unlisted
Edited
Feb 12, 2020
Fork of Diamonds
1 star
Insert cell
Insert cell
chart = {
const context = DOM.context2d(width, height, 1);
context.canvas.style.position = "absolute";
context.canvas.style.imageRendering = "pixelated";
context.canvas.style.maxWidth = "100%";
context.globalCompositeOperation = "multiply";
const div = html`
${context.canvas}
<svg viewBox="0 0 ${width} ${height}">
${d3.select(svg`<g>`).call(grid).node()}
${d3.select(svg`<g>`).call(xAxis).node()}
${d3.select(svg`<g>`).call(yAxis).node()}
</svg>
`;
let l = data.length;
for (const d of d3.shuffle(data.slice())) {
context.fillStyle = color(d);
context.fillRect(x(d.carat), y(d.price), Math.max(2, x(d.carat + 0.01) - x(d.carat)), 2);
if (--l % 100 === 0) yield div;
}
}
Insert cell
data = Object.assign(d3.tsvParse(await FileAttachment("diamonds.tsv").text(), d3.autoType), {
x: "Carats →",
y: "↑ Price $"
})
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.carat))
.rangeRound([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(data, d => d.price))
.rangeRound([height - margin.bottom, margin.top])
Insert cell
color = () => "rgba(60,180,240,0.6)"
Insert cell
grid = g => g
.attr("stroke", "currentColor")
.attr("stroke-opacity", 0.1)
.call(g => g.append("g")
.selectAll("line")
.data(x.ticks())
.join("line")
.attr("x1", d => 0.5 + x(d))
.attr("x2", d => 0.5 + x(d))
.attr("y1", margin.top)
.attr("y2", height - margin.bottom))
.call(g => g.append("g")
.selectAll("line")
.data(y.ticks())
.join("line")
.attr("y1", d => 0.5 + y(d))
.attr("y2", d => 0.5 + y(d))
.attr("x1", margin.left)
.attr("x2", width - margin.right));
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80, ".1s"))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", width)
.attr("y", margin.bottom - 4)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text(data.x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", -margin.left)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text(data.y))
Insert cell
width = 954
Insert cell
height = width
Insert cell
margin = ({top: 20, right: 20, bottom: 30, left: 40})
Insert cell
d3 = require("d3@5")
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