Published
Edited
Mar 6, 2021
Fork of Week 6
Insert cell
md`# Week 7: Tuesday`
Insert cell
md`### Pie Chart in Context2d`
Insert cell
import { outerRadius, svgPieChart, pieData} with {
viewof resetPieData,
viewof pieOptions
} from "@spattana/week-5"
Insert cell
svgPieChart
Insert cell
viewof resetPieData = button({ value: "Reset Pie Data" })
Insert cell
Insert cell
pieOptions
Insert cell
{
const svgOptions = {
width: outerRadius * 2 + 100,
height: outerRadius * 2,
margin: { top: 0, bottom: 0, left: 0, right: 0 }
};

const context = DOM.context2d(svgOptions.width, svgOptions.height);

const arcGenerator = d3
.arc()
.innerRadius(pieOptions.innerRadius)
.outerRadius(outerRadius)
.cornerRadius(5)
.context(context);

const pieGenerator = d3
.pie()
.startAngle(pieOptions.pieStart)
.endAngle(pieOptions.pieStart + pieOptions.pieDelta)
.padAngle(0.01);

const arcData = pieGenerator(pieData);

context.save();
context.translate(svgOptions.width / 2, svgOptions.height / 2);
context.fillStyle = "steelblue";
context.strokeStyle = "red";
arcData.forEach(d => {
context.beginPath();
arcGenerator(d);
context.fill();
context.stroke();
});

context.fillStyle = "black";
context.textAlighn = "center";
context.font = '10px serif';
arcData.forEach(d => {
let centroid = arcGenerator.centroid(d);
context.fillText(d.index, centroid[0], centroid[1]);
});
context.restore();

return context.canvas;
}
Insert cell
Insert cell
mutable feedback = ""
Insert cell
md`## Bubble Chart Revisit`
Insert cell
import {
drawBubbleMap,
groupeByYear,
recentYear,
years,
continents
} with { scaleOption, yearOption } from "@spattana/week-6"
Insert cell
md`### Bubble Chart from [Week 7](https://observablehq.com/@spattana/week-6#drawBubbleMap)`
Insert cell
Insert cell
Insert cell
getScales(groupeByYear.get(yearOption))
Insert cell
md`### Create Scales.`
Insert cell
getScales = data => {
const maxRad = 60;
const xScale = d3["scale" + scaleOption]()
.domain(d3.extent(data, d => d.gdpPercap))
.range([0, W])
.nice();
const yScale = d3
.scaleLinear()
.domain(d3.extent(data, d => d.lifeExp))
.range([H, 0])
.nice();
const radScale = d3
.scaleSqrt()
.domain([0, d3.max(data, d => d.pop)])
.range([2, maxRad])
.nice();

const colorScale = d3
.scaleOrdinal()
.domain(continents)
.range(d3.schemeCategory10);
return { xScale, yScale, radScale, colorScale };
}
Insert cell
md`### Bubble Chart in Canvas Version I: Bubbles only`
Insert cell
Insert cell
Insert cell
Insert cell
drawBubbleMapCanvas_I = data => {
// Create Context
const context = DOM.context2d(width, height);
context.canvas.style.background = "#EEE";

// Add Margin.
context.save();
context.translate(margin.left, margin.top);

const scales = getScales(data);

drawBubbles(context, data, scales);
return context.canvas;
}
Insert cell
drawBubbles = (context, data, scales) => {
const { xScale, yScale, radScale, colorScale } = scales;
// Draw Bubbles
context.globalAlpha = 0.5;
data.forEach(d => {
context.beginPath();
const x = xScale(d.gdpPercap),
y = yScale(d.lifeExp),
r = radScale(d.pop);
context.arc(x, y, r, 0, 2 * Math.PI);
context.fillStyle = colorScale(d.continent);
context.fill();
});
context.globalAlpha = 1.;
}
Insert cell
md`### Bubble Chart in Canvas Version II: Bubble + Axes`
Insert cell
Insert cell
drawBubbleMapCanvas_II(groupeByYear.get(yearOption))
Insert cell
drawBubbleMapCanvas_II = data => {
// Create Context
const context = DOM.context2d(width, height);
context.canvas.style.background = "#EEE";

// Add Margin.
context.save();
context.translate(margin.left, margin.top);

const scales = getScales(data);

drawBubbles(context, data, scales);

drawXaxisCanvas(context, scales.xScale);
drawYaxisCanvas(context, scales.yScale);
return context.canvas;
}
Insert cell
drawXaxisCanvas = (context, xScale) => {
let tickCount = 10,
tickSize = 6,
xTicks = xScale.ticks(tickCount),
xTickFormat = xScale.tickFormat(tickCount, ".0s");
context.strokeStyle = "black";
context.beginPath();
xTicks.forEach(function(d) {
context.moveTo(xScale(d), H);
context.lineTo(xScale(d), H + tickSize);
});
context.stroke();

context.beginPath();
context.moveTo(0, H + tickSize);
context.lineTo(0, H);
context.lineTo(W, H);
context.lineTo(W, H + tickSize);
context.stroke();

context.textAlign = "center";
context.textBaseline = "top";
context.fillStyle = "black";
xTicks.forEach(function(d) {
context.beginPath();
context.fillText(xTickFormat(d), xScale(d), H + tickSize);
});
}

Insert cell
drawYaxisCanvas = (context, yScale) => {
const tickPadding = 3,
tickCount = 10,
tickSize = 6,
yTicks = yScale.ticks(tickCount),
yTickFormat = yScale.tickFormat();
context.strokeStyle = "black";
context.beginPath();
yTicks.forEach(function(d) {
context.moveTo(0, yScale(d));
context.lineTo(-tickSize, yScale(d));
});
context.stroke();

context.beginPath();
context.moveTo(-tickSize, 0);
context.lineTo(0, 0);
context.lineTo(0, H);
context.lineTo(-tickSize, H);
context.stroke();

context.textAlign = "right";
context.textBaseline = "middle";
context.fillStyle = "black";
yTicks.forEach(function(d) {
context.beginPath();
context.fillText(yTickFormat(d), -tickSize - tickPadding, yScale(d));
});
}
Insert cell
md`### Bubble Chart in Canvas Version III: Bubbles + Axes + Interaction
Unlike SVG, Canvas does not have any element other than canvas to associate inteaction callback.
Interaction on Bubble charts are generally difficult, because larger bubbles may overlap smaller bubbles, so diffcult to access. The approach used here can be used both for SVG and Canvas bubble chart interaction.
#### Delaunay Trangulation and Voronoi Partition:
- Create a delauney triangulation fo the bubble map points. ex:
~~~
const delaunay = d3.Delaunay.from(
data,
d => xScale(d.gdpPercap),
d => yScale(d.lifeExp)
);
~~~
- Find the index of the partition (and hence index of the data point) at the event (mouse tip or touch tip) location.
~~~
const index = delaunay.find(x, y); // (x,y) are pointer location on the Canvas. eg.[x,y]= d3.pointer(event, this);
~~~
Note: Unlike in SVG, context transformation does not affect pointer location.
- Add a HTML div based tooltip at [event.pageX, event.pageY]
`
Insert cell
Insert cell
drawBubbleMapCanvas_III(groupeByYear.get(yearOption))
Insert cell
drawBubbleMapCanvas_III = data => {
// Create Context
const context = DOM.context2d(width, height);
context.canvas.style.background = "#EEE";

// Add Margin.
context.save();
context.translate(margin.left, margin.top);

const scales = getScales(data);

drawBubbles(context, data, scales);
drawXaxisCanvas(context, scales.xScale);
drawYaxisCanvas(context, scales.yScale);
addInteractionSupport(context, data, scales);

return context.canvas;
}
Insert cell
addInteractionSupport = (context, data, scales) => {
const { xScale, yScale } = scales;

const delaunay = d3.Delaunay.from(
data,
d => xScale(d.gdpPercap),
d => yScale(d.lifeExp)
);

const voronoi = delaunay.voronoi([0, 0, W, H]);

if (voronoiDrawOption == "true") {
context.globalAlpha = 0.5;
context.beginPath();
context.strokeStyle = 'rgba(0,0,0,0.3)';
voronoi.render(context);
context.stroke();
context.beginPath();
context.fillStyle = 'black';
delaunay.renderPoints(context, 2);
context.fill();
}

d3.select(context.canvas)
.on("touchmove mousemove", handleMove)
.on("touchend mouseleave", hideTooltip);
context.restore();

function handleMove(event) {
event.preventDefault();
const mousePoint = d3.pointer(event, this);
mutable feedback = [event.pageX, event.pageY, mousePoint[0], mousePoint[1]];
if (
mousePoint[0] > margin.left &&
mousePoint[0] < width - margin.right &&
mousePoint[1] > margin.top &&
mousePoint[1] < height - margin.bottom
) {
const x = mousePoint[0] - margin.left,
y = mousePoint[1] - margin.top;
const index = delaunay.find(x, y);
const country = data[index].country;
const continent = data[index].continent;
showTooltip(event, country, continent);
} else {
hideTooltip();
}
}
}
Insert cell
feedback
Insert cell
drawXaxisCanvasI = (context, xScale) => {
var tickCount = 10,
tickSize = 6,
ticks = xScale.ticks(tickCount),
tickFormat = xScale.tickFormat(8, ".0s");

context.strokeStyle = "black";
context.beginPath();
ticks.forEach(function(d) {
context.moveTo(xScale(d), H);
context.lineTo(xScale(d), H + tickSize);
});
context.stroke();

context.beginPath();
context.moveTo(0, H + tickSize);
context.lineTo(0, H);
context.lineTo(W, H);
context.lineTo(W, H + tickSize);

context.stroke();

context.textAlign = "center";
context.textBaseline = "top";
context.fillStyle = "black";
ticks.forEach(function(d) {
context.beginPath();
context.fillText(tickFormat(d), xScale(d), H + tickSize);
});
}
Insert cell
drawYaxisCanvasI = (context, yScale) => {
var tickCount = 10,
tickSize = 6,
tickPadding = 3,
ticks = yScale.ticks(tickCount),
tickFormat = yScale.tickFormat(tickCount);

// ticks
context.beginPath();
ticks.forEach(function(d) {
context.moveTo(0, yScale(d));
context.lineTo(-6, yScale(d));
});

context.beginPath();
context.moveTo(-tickSize, 0);
context.lineTo(0, 0);
context.lineTo(0, H);
context.lineTo(-tickSize, H);

context.strokeStyle = "black";
context.stroke();

// text
context.fillStyle = "black";
context.textAlign = "right";
context.textBaseline = "middle";
ticks.forEach(function(d) {
context.beginPath();
context.fillText(tickFormat(d), -tickSize - tickPadding, yScale(d));
});
}
Insert cell
tooltip = d3
.select('body')
.append('div')
.attr('class', 'canvas-tooltip')
.style('background-color', '#fff')
.style('border', '1px solid #999')
.style('border-radius', '3px')
.style(
'box-shadow',
'0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23)'
)
.style('opacity', 0)
.style('padding', '10px')
.style('position', 'absolute')
.style('pointer-events', 'none')
.style('z-index', 1)
Insert cell
function showTooltip(event, country, continent) {
tooltip
.style('opacity', 0.9)
.style('top', event.pageY + 'px')
.style('left', event.pageX + 'px')
.style('z-index', 1).html(`
<div>
country: <strong>${country}</strong>
<br>
continent: <strong>${continent}</strong>
</div>
`);
}
Insert cell
function hideTooltip() {
tooltip //d3.select('.canvas-tooltip')
.style('opacity', 0)
.style('z-index', -1);
}
Insert cell
Insert cell
voronoi = delaunay.voronoi([0, 0, W, H]);
Insert cell
pointData
Insert cell
{
const context = DOM.context2d(width, 500);
context.canvas.style.background = "#AAA";
context.translate(margin.left, margin.right);
context.fillStyle = d3.schemeCategory10[0];

context.beginPath();
voronoi.renderBounds(context);
context.fill();

context.beginPath();
voronoi.render(context);
context.stroke();

context.beginPath();
delaunay.renderPoints(context, 5);
context.fillStyle = d3.schemeCategory10[1];
context.fill();

return context.canvas;
}
Insert cell
{
const context = DOM.context2d(width, 500);
context.canvas.style.background = "#AAA";
context.translate(margin.left, margin.right);
context.fillStyle = d3.schemeCategory10[0];

context.beginPath();
voronoi.renderBounds(context);
context.fill();

d3.range(delaunay.triangles.length / 3).map(i => {
context.beginPath();
context.fillStyle = d3.schemeCategory10[2 + (i % 8)];
delaunay.renderTriangle(i, context);
context.fill();
});

context.beginPath();
delaunay.renderPoints(context, 5);
context.stroke();

return context.canvas;
}
Insert cell
{
const context = DOM.context2d(width, 500);
//context.canvas.style.background = "#AAA";
context.translate(margin.left, margin.right);

const lineGenerator = d3
.line()
.x(function(d) {
return d[0];
})
.y(function(d) {
return d[1];
})
.curve(d3.curveCatmullRomClosed)
.context(context);

const hull = Array.from(delaunay.hull);
const points = Array.from(delaunay.points);
const hullpoints = hull.map(index => [
points[index * 2 + 0],
points[index * 2 + 1]
]);

context.beginPath();
lineGenerator(hullpoints);
context.lineWidth = 1.5;
context.strokeStyle = d3.schemeCategory10[0];
context.stroke();

context.beginPath();
lineGenerator.curve(d3.curveLinear)(hullpoints);
context.lineWidth = 1.5;
context.strokeStyle = d3.schemeCategory10[1];
context.stroke();

context.beginPath();
context.strokeStyle = d3.schemeCategory10[2];
delaunay.renderPoints(context, 5);
context.stroke();

return context.canvas;
}
Insert cell
{
const context = DOM.context2d(width, height);
context.fillRect(0, 0, width, height);
context.fillStyle = "#000000";

const xScale = d3
.scalePoint()
.domain(keyCountries)
.range([0, W])
.padding(0.2);
const radScale = d3
.scaleSqrt()
.domain([0, d3.max(keyObjects, d => d.pop)])
.range([2, 60])
.nice();
const colorScale = d3
.scaleOrdinal()
.domain(continents)
.range(d3.schemeCategory10);

context.save();
context.clearRect(0, 0, width, height);
context.translate(margin.left, margin.right);
context.globalAlpha = 0.5;
keyObjects.forEach(d => {
const cx = xScale(d.country),
cy = H / 2,
r = radScale(d.pop),
color = colorScale(d.continent);
context.fillStyle = color;
context.beginPath();
//context.moveTo(cx + r, cy + r);
context.arc(cx, cy, r, 0, 2 * Math.PI);
context.fill();
});
context.globalAlpha = 1.;
context.restore();
return context.canvas;
}
Insert cell
{
const context = DOM.context2d(width, height);
context.fillRect(0, 0, width, height);
context.fillStyle = "#000000";

const xScale = d3
.scalePoint()
.domain(keyCountries)
.range([0, W])
.padding(0.2);
const radScale = d3
.scaleSqrt()
.domain([0, d3.max(keyObjects, d => d.pop)])
.range([2, 60])
.nice();
const colorScale = d3
.scaleOrdinal()
.domain(continents)
.range(d3.schemeCategory10);

const bubbles = d3
.select(context.canvas)
.append("custom")
.selectAll("circle")
.data(keyObjects)
.join("circle")
.attr('cx', d => xScale(d.country))
.attr('cy', H / 2)
.attr("r", d => radScale(d.pop))
.style("fill", d => colorScale(d.continent))
.style("opacity", 0.5);

context.save();
context.clearRect(0, 0, width, height);
context.translate(margin.left, margin.right);
bubbles.each((d, i, l) => {
const node = d3.select(l[i]);
/*
context.fillStyle = node.style('fill');
context.fillRect(
node.attr('cx') - node.attr('r'),
node.attr('cy') - node.attr('r'),
node.attr('r') * 2,
node.attr('r') * 2
);
*/
const cx = node.attr('cx'),
cy = node.attr('cy'),
r = node.attr('r');
context.beginPath();
//context.moveTo(cx + r, cy + r);
context.arc(cx, cy, r, 0, 2 * Math.PI);
context.fillStyle = node.style('fill');
context.fill();
});
context.restore();
return context.canvas;
}
Insert cell
md`## Data`
Insert cell
Insert cell
margin = ({ top: 20, right: 30, bottom: 30, left: 40 })
Insert cell
height = 500
Insert cell
H = height - margin.top - margin.bottom
Insert cell
W = width - margin.left - margin.bottom
Insert cell
md`## External Libraries, Imports`
Insert cell
import { AxisAnatomy } from "@spattana/drawing-axis-in-d3-canvas"
Insert cell
import { generateRandomPointData } with { W, H } from "@spattana/week-5"
Insert cell
import { getSVG } with { width, height, margin } from "@spattana/week-5"
Insert cell
import { Table } from "@observablehq/inputs"
Insert cell
import { radio, select, slider, button } from "@jashkenas/inputs"
Insert cell
import { columns } from "@bcardiff/observable-columns"
Insert cell
d3 = require("d3@6")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more