Published
Edited
Oct 9, 2018
1 fork
Insert cell
Insert cell
chart = {
// Elemento SVG do diagrama
const svg = d3.select(DOM.svg(width, height))
.attr("viewBox", [-width / 2, -height / 2, width, height])
.attr("font-size", 10)
.attr("font-family", "sans-serif");

// Referência ao d3.chord (ver função na célula chord), tranforma a matriz de entrada
// em um objeto para o chord diagram
const chords = chord(data);

// Associa os dados do diagrama com o DOM
const group = svg.append("g")
.selectAll("g")
.data(chords.groups)
.enter().append("g");

// Cria arco externo, chama arc (ver célula arc)
group.append("path")
.attr("fill", d => color(d.index))
.attr("stroke", d => d3.rgb(color(d.index)).darker())
.attr("d", arc);
const groupTick = group.append("g")
.selectAll("g")
.data(d => groupTicks(d, 1e3))
.enter().append("g")
.attr("transform", d => `rotate(${d.angle * 180 / Math.PI - 90}) translate(${outerRadius},0)`);
// Cria as linhas de contagem (ticks)
groupTick.append("line")
.attr("stroke", "#000")
.attr("x2", 6);
// Cria os labels
groupTick
.filter(d => d.value % 5e3 === 0)
.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("transform", d => d.angle > Math.PI ? "rotate(180) translate(-16)" : null)
.attr("text-anchor", d => d.angle > Math.PI ? "end" : null)
.text(d => formatValue(d.value));
// Cria as "cordas"
svg.append("g")
.attr("fill-opacity", 0.67)
.selectAll("path")
.data(chords)
.enter().append("path")
.attr("d", ribbon)
.attr("fill", d => color(d.target.index))
.attr("stroke", d => d3.rgb(color(d.target.index)).darker());
// Retorna o objeto SVG (necessário no Observable)
return svg.node();
}
Insert cell
Insert cell
data = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
]
Insert cell
function groupTicks(d, step) {
const k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, step).map(value => {
return {value: value, angle: value * k + d.startAngle};
});
}
Insert cell
Insert cell
formatValue = d3.formatPrefix(",.0", 1e3)
Insert cell
Insert cell
chord = d3.chord()
.padAngle(0.05)
.sortSubgroups(d3.descending)
Insert cell
Insert cell
arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
Insert cell
Insert cell
ribbon = d3.ribbon()
.radius(innerRadius-5)
Insert cell
Insert cell
color = d3.scaleOrdinal()
.domain(d3.range(4))
.range(["#000000", "#FFDD89", "#957244", "#F26223"])
Insert cell
Insert cell
outerRadius = Math.min(width, height) * 0.5 - 30
Insert cell
Insert cell
innerRadius = outerRadius - 20
Insert cell
Insert cell
height = Math.min(640, width)
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