JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.js"></script>
CSS
.background-piece {
fill: #ccc;
}
.label {
font-size: 1.6rem;
}
.label-main {
fill: #717171;
}
JavaScript
// ===============================
// QUESTION:
// How can this handle more than 2 pieces without explicitly choosing colors?
var color = d3.scale.ordinal()
.range(['#0075B4', '#70B5DC']);
// ===============================
var data = {
charges: [
{
name: 'Cost 1',
amount: 0.34,
rate: 'hourly'
},
{
name: 'Cost 2',
amount: 0.13,
rate: 'hourly'
},
{
name: 'Cost 3',
amount: 0.19,
rate: 'hourly'
}
],
hoursPerDay: 24,
daysPerMonth: 30
}
var container = document.body;
var classes = {
container: 'container',
arc: 'arc',
piece: 'piece',
background: 'background',
backgroundPiece: 'background-piece',
label: 'label',
labelMain: 'label-main',
labelSub: 'label-sub'
}
// Set up svg attributes
var width = 530;
var height = 430;
var chartWidth = 300;
var chartHeight = 300;
var radius = Math.min(chartWidth, chartHeight) / 2;
var labelRadius = radius + 55;
var strokeThickness = 17;
// Determine the thickness of the donut chart
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - strokeThickness);
// Create a pie chart using amount as the value for the pieces
var chart = d3.layout.pie()
.sort(function (a, b) {
return d3.ascending(a.amount, b.amount);
})
.value(function (d) {
return d.amount;
});
// Create the svg element where the chart will render
var svg = d3.select(container)
.append('svg:svg')
.attr('class', classes.container)
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
// Create background
var background = svg.append('svg:g')
.data([{
startAngle: 0,
endAngle: 360
}])
.attr('class', classes.background);
// Add background piece
background.append('svg:path')
.attr('class',...