Skip to content

Instantly share code, notes, and snippets.

@willroj
Last active May 1, 2017 22:27
Show Gist options
  • Save willroj/516a4cfbce9d0337bf612c729187b2f7 to your computer and use it in GitHub Desktop.
Save willroj/516a4cfbce9d0337bf612c729187b2f7 to your computer and use it in GitHub Desktop.
Pie Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.arc text {
fill: white;
font-weight: bold;
}
.arc. path {
stroke: red;
/* stroke-width: 2; */
}
.title {
font-size: 1.5rem;
font-weight: 700;
/* text-decoration: underline; */
text-transform: Capitalize;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var width = 960,
height = 500,
margin = 50,
colors = [
'rgba(142, 68, 173,1.0)',
'rgba(41, 128, 185,1.0)',
'rgba(22, 160, 133,1.0)'
],
classes = ['1st Class', '2nd Class', '3rd Class'];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
var title =svg.append('g')
.append('text')
.attr('class', 'title')
.text('Distribución por categoría')
var TITLE_LENGTH = Number.parseInt(title.style('width').substr(0,3))
//center the title over the chart (I know i did this the hardway)
title.attr('transform', `translate(${(width / 2) - (TITLE_LENGTH / 2)}, ${margin})`)
var chart = svg.append('g')
.attr('transform', `translate(${width / 2}, ${height / 1.8})`)
var arc = d3.arc()
.innerRadius(1)
.outerRadius(200)
.padRadius(20)
var pie = d3.pie()
.padAngle(.1);
d3.json('Titanic.json', function(d) {
var survivors = d.filter(function(el) {
if(Number.parseInt(el.Survived)) {
return el
}
})
var NUM_1_CLASS = survivors.filter(function(el) {
if(el.PClass === '1st') {
return el
}
}).length
var NUM_2_CLASS = survivors.filter(function(el) {
if(el.PClass === '2nd') {
return el
}
}).length
var NUM_3_CLASS = survivors.filter(function(el) {
if(el.PClass === '3rd') {
return el
}
}).length
var sections = [
NUM_1_CLASS,
NUM_2_CLASS,
NUM_3_CLASS
];
chart = chart.selectAll('.arc')
.data(pie(sections))
.enter()
.append('g')
.attr('class', 'arc')
chart.append('path')
.attr('d', arc)
.attr('fill', function(d, i) { return colors[i]})
chart.append('text')
.attr('transform', function(d){ return `translate(${arc.centroid(d)})`})
.text(function(d, i) {return classes[i]})
})
</script>
</body>
PClass Survived
1st 1
1st 1
2nd 1
3rd 1
3rd 1
3rd 1
[{"PClass":"1st","Survived":1},
{"PClass":"1st","Survived":1},
{"PClass":"2nd","Survived":1},
{"PClass":"3rd","Survived":1},
{"PClass":"3rd","Survived":1},
{"PClass":"3rd","Survived":1}]
[{"text":"1st","categoria":"Pos"},
{"text":"1st","categoria":"Neu"},
{"text":"2nd","categoria":"Neu"},
{"text":"3rd","categoria":"Neu"},
{"text":"3rd","categoria":"Neg"},
{"text":"3rd","categoria":"Neg"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment