Public
Edited
Nov 4, 2022
1 fork
Insert cell
Insert cell
chart = {
const svg = d3.create('svg')
.attr('viewBox', [0, 0, width, height])
.attr('style', 'border: 1px solid #eee')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr("viewBox", [-width / 2, -height / 2, width, height]);

svg.append("g")
.selectAll("path")
.data(pieArcData)
.join("path")
.attr("fill", d => color(d.data[seriesField]))
.attr("d", arcPie)
.attr('title', d => `${d.data[seriesField]}: ${(d.data[yField])}`);

svg.append("g")
.selectAll("polyline")
.data(pieArcData)
.join("polyline")
.attr("stroke", "#aaa")
.attr("opaticy", ".3")
.attr("stroke-width", "1px")
.attr("fill", "none")
.attr("points", (d) => {
const pos = arcLabel.centroid(d);
const pieCenter = arcPie.centroid(d);
pos[0] = labelRadius * 0.95 * (midAngle(d) < Math.PI ? 1 : -1);
return [pieCenter, arcLabel.centroid(d), pos];
});

svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("fill", "black")
.selectAll("text")
.data(pieArcData)
.join("text")
.attr("transform", (d) => {
var baro = ~~Math.log10(d.data.value/10)/2 + 1;
var pos = arcLabel.centroid(d);
pos[0] = labelRadius * (midAngle(d) < Math.PI ? 1 : -1);
return `translate(${pos})`;
})
.attr("text-anchor", d => midAngle(d) < Math.PI ? "start" : "end")
.text(d => `${d.data[seriesField]} ${d.data[yField]}`);

svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("text-anchor", "middle")
.attr("fill", "#fff")
.selectAll("text")
.data(pieArcData)
.join("text")
.attr("transform", (d) => {
const pieCenter = arcPie.centroid(d);
return `translate(${pieCenter})`;
})
// .attr("text-anchor", d => midAngle(d) < Math.PI ? "start" : "end")
.text(d => {
const proportion = d.value / dataTotal * 100;
return `${proportion.toFixed(2)}%`;
});


return svg.node();
}

Insert cell
color = d3.scaleOrdinal()
.domain(pieData.map(d => d[seriesField]))
.range(colors[1])
Insert cell
midAngle = (d) => {
return d.startAngle + (d.endAngle - d.startAngle)/2;
}
Insert cell
arcLabel = d3.arc().innerRadius(labelRadius).outerRadius(labelRadius);
Insert cell
arcPie = {
return d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.padRadius(0)
.padAngle(0)
.cornerRadius(cornerRadius);
}
Insert cell
pieArcData = d3.pie().padAngle(0)
.sort(enabledSort ? (a, b) => b.value - a.value : null)// .sortValues((a, b) => b - a)
.value(d => d.value)(pieData);
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
dataCategory = getCategories(data, seriesField)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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