Published
Edited
Jan 21, 2021
1 fork
Insert cell
md`# Simple Gauge Chart`
Insert cell
viewof chart = {
const svg = d3.select(DOM.svg(width, height));

svg.append('rect')
.attr('class', 'bg')
.attr('width', width)
.attr('height', height)
.attr('fill', '#999');

const minValue = Math.min(...config.sections.map(d => d.from));
const maxValue = Math.max(...config.sections.map(d => d.to));
const scale = d3.scaleLinear()
.domain([minValue, maxValue])
.range([
config.panel.startAngle,
config.panel.endAngle
]);
const radius = Math.floor(Math.max(width, height) / 2) - 2;
const arc = d3.arc()
.outerRadius(radius)
.innerRadius(radius - config.panel.width);

const inner = svg
.append('g')
.attr('transform', `translate(${width/2},${height/2})`);
const needle = inner
.append('g')
.attr('class', 'needle')
.attr('fill', '#fff')
.call(s => s
.append('circle')
.attr('r', 9)
)
.call(s => s
.append('rect')
.attr('x', -2)
.attr('y', -height * .35)
.attr('width', 4)
.attr('height', height * .35)
)
.attr('transform', `rotate(scale(0))`)
.transition()
.ease(d3.easeElastic.amplitude(.25).period(1))
.duration(1000)
.attr('transform', `rotate(${scale(Math.random() * maxValue)})`);
inner
.selectAll('path.arc')
.data(config.sections)
.join('path')
.attr('class', 'arc')
.attr('d', d => arc({
startAngle: deg2rad(scale(d.from)),
endAngle: deg2rad(scale(d.to))
}))
.attr('fill', d => d.color)
.attr('stroke', '#fff')
.attr('stroke-width', '2px');
return svg.node();
}
Insert cell
function deg2rad(deg) { return Math.PI / 180 * deg; }
Insert cell
md `### Config`
Insert cell
width = 400
Insert cell
height = 400
Insert cell
config = ({
panel: {
startAngle: -120,
endAngle: 120,
width: 40
},
sections: [
{ from: 0, to: 25, color: '#f00' },
{ from: 25, to: 50, color: '#ff0' },
{ from: 50, to: 150, color: '#0f0' },
{ from: 150, to: 175, color: '#ff0' },
{ from: 175, to: 200, color: '#f00' },
]
});
Insert cell
md `### Globals`
Insert cell
d3 = require(
'd3-ease',
'd3-scale',
'd3-selection',
'd3-shape',
'd3-transition'
)
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