Published
Edited
Jun 26, 2019
1 fork
2 stars
Insert cell
md`# speedometer`
Insert cell
data = ({"total": 100, "value": 20, "goal": 25})
Insert cell
chart = {
const arcs = pie([{name: "goal", value: data.goal, color: "#FC575E"}, {name: "", value: data.total-data.goal}]);
const colors = {"color1": "#FC575E", "color2": "#09203F"}
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("text-anchor", "middle")
.style("font", "12px sans-serif");

const g = svg.append("g")
.attr("transform", `translate(${width / 2},${height / 1.5})`);
const gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")

gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", colors.color1)
.attr("stop-opacity", 1);

gradient.append("svg:stop")
.attr("offset", "75%")
.attr("stop-color", colors.color2)
.attr("stop-opacity", 1);
g.selectAll("path")
.data(arcs)
.join("path")
.attr('fill', (d) => {
console.log(d)
if(d.data.name != ''){
return d.data.color;
}else{
return 'url(#gradient)';
}
})
.attr("d", arc)
const rect = g
.append("rect")
.attr("x", -5)
.attr("y", 0)
.attr("width", 10)
.attr("height", 275)
.attr("fill", colors.color2)
.attr("stroke", colors.color2)
//.attr("stroke-width", "4px")
.attr("transform", `rotate(${180-105})`)
.transition()
.duration(750)
.attr("transform", `rotate(${angle+180})`)
const circle = g
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
//.attr("dy", 15)
.attr("r", 10)
.attr("fill", colors.color2)
const text = g.selectAll("text")
.data(arcs)
.join("text")
.attr("transform", d => `translate(${arc.centroid(d)})`)
.attr("dy", "0.35em");
text.append("tspan")
.attr("x", 0)
.attr("y", "-0.7em")
.attr("font-size", "18px")
.style("font-weight", "bold")
.text(d => d.data.name);
text.filter(d => (d.endAngle - d.startAngle)).append("tspan")
.attr("x", 0)
.attr("y", "0.7em")
.attr("font-size", "24px")
.attr("fill-opacity", 0.7)
.text(d => {
if(d.data.name != ''){
return d.data.value.toLocaleString()+'%';
}
});
const p = g
.append("text")
.text(`${Math.round((data.value/data.total)*100)}%`)
.attr("x", 0)
.attr("y", 60)
.attr("font-size", "35px")
return svg.node();
}
Insert cell
height = Math.min(width, 500)
Insert cell
arc = {
const radius = Math.min(width, height) / 2;
return d3.arc().innerRadius(radius * 0.67).outerRadius(radius - 1);
}
Insert cell
pie = d3.pie()
.startAngle(-105 * (Math.PI/180))
.endAngle(105 * (Math.PI/180))
.sort(null)
.value(d => d.value)
Insert cell
d3 = require("d3@5")
Insert cell
angle = ((210*data.value)/data.total) - 105
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