Range Pie Chart - D3js
Dynamic D3js pie chart + synchronizing HTML5 sliders.
HTML
<form id=nbForm>
<table>
<tbody>
<tr>
<td>Nb sliders</td>
<td>
<input id=nbSliders type="number" min="2" max="10" value="2"/>
</td>
<td><button id=nbFormSubmit>OK</button></td>
</tr>
</tbody>
</table>
</form>
<table id=rangebox>
<tbody>
</tbody>
</table>
<div id=pie></div>
CSS
html{
font-family: calibri, arial;
}
table td{
padding: 5px;
}
#nbForm{
margin-bottom: 20px;
}
#rangebox{
table-layout: fixed;
border-collapse: collapse;
float: left;
width: 50%;
margin-right: 20px;
}
#rangebox td.edit{
border: 1px dashed silver;
cursor: text;
}
#rangebox td.edit:hover, #rangebox td.edit:focus{
background-color: LemonChiffon;
}
#rangebox td:nth-child(1){
width: 25%;
}
#rangebox td:nth-child(3){
text-align: center;
width: 10%;
}
#rangebox input{
width: 100%;
cursor: pointer;
}
#pie{
float: left;
width: 300px;
height: 300px;
font-weight: bold;
}
text{
pointer-events: none;
}
path{
cursor: help;
transition: opacity 0.5s;
-moz-transition: opacity 0.5s;
-webkit-transition: opacity 0.5s;
}
path:hover{
opacity: 0.75;
}
JavaScript
var nb_sliders = null; // nb of range sliders
var moving_id = null; // id of the moved slider
var oldValue = []; // previous values of the sliders
var radius = 150; // pie chart radius
var color = d3.scale.category20(); // color scheme (10, 20, 20b, 20c ...)
var pi = Math.PI; // 3.14
// pie chart config
var pie = d3.layout.pie()
.value(function(d) { return d.value; })
//.startAngle(-90 * (pi/180))
//.endAngle(90 * (pi/180))
.sort(null);
// arc object
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius/2);
// nb sliders event
d3.select('#nbFormSubmit').on('click', function()
{
d3.event.preventDefault();
nb_sliders = d3.select('#nbSliders')[0][0].value;
init();
});
// initialize the sliders, events and pie chart
function init()
{
oldValue = [];
moving_id = null;
d3.select('#rangebox tbody').html('');
// append sliders to table
for(i=0; i<nb_sliders; i++)
{
var tr = d3.select('#rangebox tbody').append('tr');
tr.append('td')
.attr('class', 'edit')
.attr('contenteditable', true)
.text('Label '+(i+1));
tr.append('td')
.append('input')
.attr('type', 'range')
.attr('data-id', i)
.attr('class', 'range')
.attr('step', 1)
.attr('min', 0)
.attr('max', 100);
tr.append('td')
.attr('class', 'range_value');
}
d3.selectAll('#rangebox .range').each(function(){
var def = parseInt(100 / nb_sliders);
this.value = def;
oldValue[d3.select(this).attr('data-id')] = this.value;
});
equalize();
showValues();
pieChart();
// content edit event
d3.selectAll('.edit').on('input', function(){
updateLabels();
});
// slider event
d3.selectAll('.range').on('change', function()
...