Public
Edited
Apr 1, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = (dataset) => {
// Specify the chart’s dimensions.
const width = 1080;
const height = 720;

let data = dataset;

for (const d of data) {
console.log("Name:" + d.name + " Value:" + d.value);
}

const color = d3.scaleOrdinal()
.domain(dataset.map(d => d.name))
.range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), dataset.length).reverse());

const pie = d3.pie()
.sort(null)
.value(d => d.value);

const arc = d3.arc()
.innerRadius(0)
.outerRadius(Math.min(width, height) / 2 - 1);

const labelRadius = arc.outerRadius()() * 0.8;

const arcLabel = d3.arc()
.innerRadius(labelRadius)
.outerRadius(labelRadius);

const arcs = pie(dataset);

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height])
.attr("style", "max-width: 100%; height: auto; font: 10px sans-serif;");

svg.append("g")
.attr("stroke", "white")
.selectAll()
.data(arcs)
.join("path")
.attr("fill", d => color(d.data.name))
.attr("d", arc)
.append("title")
.text(d => `${d.data.name}: ${d.data.value}`);

svg.append("g")
.attr("text-anchor", "middle")
.selectAll()
.data(arcs)
.join("text")
.attr("transform", d => `translate(${arcLabel.centroid(d)})`)
.call(text => text.append("tspan")
.attr("y", "-0.4em")
.attr("font-weight", "bold")
.attr("fill", "purple")
.text(d => "Hours Spent " + d.data.name))
.call(text => text.filter(d => (d.endAngle - d.startAngle) > 0.25).append("tspan")
.attr("x", 0)
.attr("y", "0.7em")
.attr("fill-opacity", 0.7)
.attr("fill", "purple")
.text(d => d.data.value + " Hours" + "-- " + ((d.data.value/168)*100).toFixed(2) + "%"));

const legendScale = d3
.scaleOrdinal()
.domain(dataset.map((d) => d.name))
.range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), dataset.length).reverse());
var legendOrdinal = d3Legend
.legendColor()
.shape("path", d3.symbol().type(d3.symbolSquare).size(60)())
.shapePadding(20)
.orient("vertical")
.scale(legendScale);

svg.append("g").attr("transform", "translate(400,20)").call(legendOrdinal);

return svg.node();
}
Insert cell
dataset = await FileAttachment("my-data@1.csv").csv({typed: true});
Insert cell
d3 = require("d3@7")
Insert cell
d3Legend = require('d3-svg-legend')
Insert cell
my-data@1.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

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