Donut chart d3 v4
by Rich Costello
HTML
<div class="content">
<svg id="donut-chart"></svg>
<svg id="legend"></svg>
</div>
SCSS
@import url(https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic);
* {
font-family: Roboto;
}
#legend
.content h1 {
font-weight: 500;
text-align: center;
}
svg#donut-chart {
display: block;
margin: 0 auto;
}
text.inner-circle {
font-weight: 400;
font-size: 15px;
text-transform: uppercase;
}
.arc {
cursor: pointer;
&:hover {
opacity: .85;
}
text {
font-weight: 300;
font-size: 18px;
color: #fff;
}
}
JavaScript
// Seed data to populate the donut pie chart
var seedData = [{
"label": "Without Feedback XX%",
"value": 25,
"link": "https://google.com"
}, {
"label": "With Feedback XX%",
"value": 75,
"link": "https://yahoo.com"
}];
// Define size & radius of donut pie chart
var width = 200,
height = 200,
radius = Math.min(width, height) / 2;
// Define arc colors
var color = d3.scaleOrdinal()
.range(["#62B5E5","#FBD507"]);
// Define arc ranges
var arcText = d3.scaleOrdinal()
.range([0, width]);
// Determine size of arcs
var arc = d3.arc()
.innerRadius(radius - 40)
.outerRadius(radius - 10);
// Create the donut pie chart layout
var pie = d3.pie()
.value(function (d) { return d["value"]; })
.sort(null);
// Append SVG attributes and append g to the SVG
var svg = d3.select("#donut-chart")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Define inner circle
svg.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", 100)
.attr("fill", "#fff") ;
// Calculate SVG paths and fill in the colors
var g = svg.selectAll(".arc")
.data(pie(seedData))
.enter().append("g")
.attr("class", "arc")
// Make each arc clickable
.on("click", function(d, i) {
window.location = seedData[i].link;
});
// Append the path to each g
g.append("path")
.attr("d", arc)
.attr("fill", function(d, i) {
return color(i);
});
// Append text labels to each arc
g.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.attr("fill", "#fff");
// Append text to the inner circle
svg.append("text")
.attr("dy", "-0.5em")
.style("text-anchor", "middle")
.attr("class", "inner-circle")
.attr("fill", "#36454f")
.text(function(d) { return 'XX'; });
svg.append("text")
.attr("dy", "1.0em")
.style("text-anchor", "middle")
...