Skip to content

Instantly share code, notes, and snippets.

@manojwajekar
Last active April 14, 2018 02:43
Show Gist options
  • Save manojwajekar/9dd60f4b55f498b6d3095c081138cae4 to your computer and use it in GitHub Desktop.
Save manojwajekar/9dd60f4b55f498b6d3095c081138cae4 to your computer and use it in GitHub Desktop.
Pie_Chart_With%
license: mit
[{"total": 5, "leads_intended_storage_duration_tiers": "3 to 5"}, {"total": 3, "leads_intended_storage_duration_tiers": "Below 3"}, {"total": 4, "leads_intended_storage_duration_tiers": "Undefined"},{"total": 4, "leads_intended_storage_duration_tiers": "5 to 10"},{"total": 2, "leads_intended_storage_duration_tiers": "More than 12"}]
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.arc text {
font: 12px sans-serif;
text-anchor: middle;
font-weight: bold;
}
.arc path {
stroke: #fff;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = Math.min(width, height) / 2.25,
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var color = d3.scaleOrdinal(['#67bf5c','#ff9e4a','#6dccda','#ad8bc9','#ed665d', '#cdcc5d', '#a8786e', '#729ece', '#a2a2a2','#ed97ca']);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.total; });
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var label = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var percentageFormat = d3.format(".2%",);
/*
d3.csv("data.csv", function(d) {
d.population = +d.population;
return d;
}, function(error, data) {
if (error) throw error;*/
d3.json("data.json", function(error, data) {
var tots = d3.sum(data, function(d) {
return d.total;
});
data.forEach(function(d) {
// d.leads_intended_storage_duration_tiers = (d.leads_intended_storage_duration_tiers);
d.total = +d.total;
d.percentage = d.total / tots;
});
var arc = g.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
arc.append("path")
.attr("d", path)
.attr("fill", function(d) { return color(d.data.leads_intended_storage_duration_tiers); });
arc.append("text")
.attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
.attr("dy", "0.35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.leads_intended_storage_duration_tiers; })
arc.append("text")
.attr("transform", function(d) {
var _d = path.centroid(d);
_d[0] *= 2.3; //multiply by a constant factor
_d[1] *= 2.3; //multiply by a constant factor
return "translate(" + _d + ")";
})
.attr("dy", ".50em")
.style("text-anchor", "middle")
.text(function(d) {
console.log("d is", d);
return percentageFormat(d.data.percentage);})
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment