Skip to content

Instantly share code, notes, and snippets.

@akulmehta
Last active April 15, 2019 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akulmehta/183847663739b944038ad973e0b7d5b4 to your computer and use it in GitHub Desktop.
Save akulmehta/183847663739b944038ad973e0b7d5b4 to your computer and use it in GitHub Desktop.
Lydias Pie Chart
license: mit
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="shortcut icon" href="icons8-bookmark-40.png">
<!-- JS libraries -->
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class="col-md-9" id="pie-chart-area"></div>
<!-- Custom JS -->
<script src="main.js"></script>
</body>
</html>
function getGenderColor(genderColor) {
var fill;
switch(genderColor) {
case "M":
fill = "#0079BB";
break;
case "F":
fill = "#9E519F";
break;
default:
fill = "blue";
}
return fill;
}
function pieChart(chartArea) {
var margin = {left:40, right:40, top:40, bottom:40};
var width = 500 - margin.top - margin.bottom,
height = 800 - margin.left - margin.right;
var radius = Math.min(width, height) / 2;
var donutWidth = 75;
// color range
var color = d3.scaleOrdinal()
.range(["#0079BB", "#9E519F"]);
// entire canvas
var svg = d3.select(chartArea)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("s_gender.json", function(error,data) {
/*if (error) return console.error(error);
console.log('mockdata',data);*/
data.forEach(function(d) {
d.count = +d.count;
});
//define arc
var arc = d3.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
// import pie chart and data
var pie = d3.pie()
.value(function(d) { return d.count; })
.sort(null);
var path = svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return getGenderColor(d.data.gender);
});
});
}
pieChart("#pie-chart-area");
[
{
"gender":"F",
"count":533
},
{
"gender":"M",
"count":260
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment