84 lines
2.9 KiB
JavaScript
84 lines
2.9 KiB
JavaScript
|
'use strict';
|
||
|
var DonutChart = {
|
||
|
init: function(url, html_tag_attr, label_accessor, value_accessor, color_accessor, inner_radius=80){
|
||
|
this.url = url;
|
||
|
this.html_tag_attr = html_tag_attr;
|
||
|
|
||
|
this.label_accessor = label_accessor;
|
||
|
this.value_accessor = value_accessor;
|
||
|
this.color_accessor = color_accessor;
|
||
|
this.inner_radius = inner_radius;
|
||
|
|
||
|
this.render();
|
||
|
this.update();
|
||
|
},
|
||
|
prepare_data: function(){
|
||
|
var self = this;
|
||
|
return d3.json(urlRoot+this.url, config_requestArguments).then(function(dataset){
|
||
|
self.data = [];
|
||
|
var total_val = d3.sum(dataset, self.value_accessor);
|
||
|
dataset.forEach(function(d){
|
||
|
self.data.push({
|
||
|
label: self.label_accessor(d),
|
||
|
value: self.value_accessor(d) / total_val * 100,
|
||
|
value_raw: self.value_accessor(d),
|
||
|
color: self.color_accessor(d)
|
||
|
})
|
||
|
});
|
||
|
});
|
||
|
},
|
||
|
render: function(){
|
||
|
this.svg = d3.select(this.html_tag_attr).append("svg");
|
||
|
this.pie_group = this.svg
|
||
|
.append("g");
|
||
|
},
|
||
|
update: function(){
|
||
|
var self = this;
|
||
|
this.prepare_data().then(function(){
|
||
|
var width = $(self.svg.node()).width();
|
||
|
var height = $(self.svg.node()).height();
|
||
|
var mini_dim = d3.min([width, height]);
|
||
|
var margin = mini_dim * 0.05;
|
||
|
var outerRadius = (mini_dim / 2) - margin;
|
||
|
var innerRadius = outerRadius * self.inner_radius / 100;
|
||
|
var group_vertical_position = height / 2
|
||
|
var group_horizontal_position = width / 2
|
||
|
|
||
|
var pie = d3.pie()
|
||
|
.value(function(d){ return d.value; });
|
||
|
|
||
|
var arc = d3.arc()
|
||
|
.outerRadius(outerRadius)
|
||
|
.innerRadius(innerRadius);
|
||
|
|
||
|
self.pie_group
|
||
|
.attr("transform", "translate(" + group_horizontal_position + "," + group_vertical_position + ")")
|
||
|
.selectAll("path")
|
||
|
.data(pie(self.data))
|
||
|
.enter()
|
||
|
.append("path");
|
||
|
|
||
|
self.pie_group
|
||
|
.selectAll("path")
|
||
|
.attr("d", function(d){ return arc(d); })
|
||
|
.attr("fill", function(d){ return self.color_accessor(d.data); });
|
||
|
});
|
||
|
},
|
||
|
}
|
||
|
|
||
|
// Exemple d'utilisation :
|
||
|
// get_donut_chart(
|
||
|
// "custom/script/ajax/my_kpi.php",
|
||
|
// "my_html_tag_attr",
|
||
|
// function(d){ return d.label; },
|
||
|
// function(d){ return d.value; },
|
||
|
// function(d){ return d.color; },
|
||
|
// 0.75
|
||
|
// );
|
||
|
var get_donut_chart = function(url, html_tag_attr, label_accessor, value_accessor, color_accessor, inner_radius=80){
|
||
|
var my_donut = {};
|
||
|
Object.assign(my_donut, DonutChart);
|
||
|
my_donut.init(url, html_tag_attr, label_accessor, value_accessor, color_accessor, inner_radius);
|
||
|
return my_donut;
|
||
|
};
|