Simple Pie Chart with NVD3
An example of a simple pie chart drawn with NVD3
by sathish panduga p
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.css">
<div id="chart">
<svg></svg>
</div>
CSS
@import url(http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans+Mono);
#chart svg {
height: 600px;
}
.nv-label text{
font-family: Droid Sans;
}
JavaScript
var h = 600;
var r = h/2;
var arc = d3.svg.arc().outerRadius(r);
var data = [
{"label":"Colorectale levermetastase (n=336)", "value":74},
{"label":"Levensmetatase van andere origine (n=32)", "value":7},
{"label":"Beningne levertumor (n=34)", "value":7},
{"label": "Primaire maligne levertumor (n=56)", "value":12}
];
var colors = [
'rgb(178, 55, 56)',
'rgb(213, 69, 70)',
'rgb(230, 125, 126)',
'rgb(239, 183, 182)'
]
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.color(colors)
.showLabels(true)
.labelType("percent")
// .donut(true).donutRatio(0) /* Trick to make the labels go inside the chart*/
;
d3.select("#chart svg")
.datum(data)
.transition().duration(1200)
.call(chart)
;
d3.selectAll(".nv-label text")
/* Alter SVG attribute (not CSS attributes) */
.attr("transform", function(d){
d.innerRadius = -450;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";}
)
.attr("text-anchor", "middle")
/* Alter CSS attributes */
.style({"font-size": "1em"})
;
/* Replace bullets with blocks */
d3.selectAll('.nv-series').each(function(d,i) {
var group = d3.select(this),
circle = group.select('circle');
var color = circle.style('fill');
circle.remove();
var symbol = group.append('path')
.attr('d', d3.svg.symbol().type('square'))
.style('stroke', color)
.style('fill', color)
// ADJUST SIZE AND POSITION
.attr('transform', 'scale(1.5) translate(-2,0)')
});
return chart;
});