JSFiddle - React, Tailwind, and code Playground
by spaccamontagna
HTML
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg class="chart">Chart loading...</svg>
CSS
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
JavaScript
mytarget = ".chart";
mycsvData = `status,count
pending,2
running,15
shutting-down,0
terminated,0
stopping,0
stopped,29`;
function myPieChart(target, csvData) {
if (typeof(target) == "undefined" || target=="") target=".chart";
jQuery(target).children().remove();
jQuery(target).html('<div class="chartLoading">Loading...</div>');
// define sizes and slices colors
var width = 250,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal()
.range(["#FC0", "#39C", "#98abc5", "#7b6888", "#a05d56", "#ff8c00"]);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 80);
var svg = d3.select(target)
.attr("width", width * 2)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// parse data
var parsedData = d3.csvParse(csvData, function(d) {
return {
status:d.status,
count:+d.count
};
});
// calculate the total number of active instances
var sum = d3.sum(parsedData, function(d) { return d.count; });
if (sum == 0)
parsedData = [{ status: "none", count: "100"}];
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.count });
var g = svg.selectAll(".arc")
.data(pie(parsedData))
.enter().append("g")
.attr("class", "arc");
// build pie
g.append("path")
.style("fill", function(d) { if (sum==0) { return "#dddddd" }
else {return color(d.data.status); }})
.transition().delay(function(d, i) { return i * 500; }).duration(500)
.attrTween('d', function(d) {
var i = d3.interpolate(d.startAngle+0.1, d.endAngle);
return function(t) {
if (d.value!=0) {
d.endAngle = i(t);
return arc(d);
}
};
});
...