Skip to content

Instantly share code, notes, and snippets.

@MrJackdaw
Created August 26, 2015 18:10
Show Gist options
  • Save MrJackdaw/ba6ae35d28b9a1236516 to your computer and use it in GitHub Desktop.
Save MrJackdaw/ba6ae35d28b9a1236516 to your computer and use it in GitHub Desktop.
Function for generating a two-color pie chart using D3. Assumes d3 is included and accessible in current scope.
/**
* Params below: use as-is to generate a hollow two-figure pie chart (donut chart)
* @var[width]: pie chart width
* @var[height]: pie chart height
* @var[innerRadius]: inner (hollow) circle radius
* @var[colorRange]: first and second (respective) colors rendered in pie chart
* @var
*/
var width = 90,
height = 90,
innerRadius = Math.round((5/12) * width);
var radius = Math.min(width, height) / 2,
colorRange = ['#64abdb', '#f2f2f2'], // light-blue, gray
svg, item, value;
var m = document.getElementById('myElement'); // Target your element here
value = 33;
generatePieChart(m, value);
function generatePieChart(elem, value){
elem.innerHTML = '';
// PIE CHART GENERATOR
svg = d3.select(elem).append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
renderCharts([value, 100 - value]);
function renderCharts(data) {
// Render pie chart
var color = d3.scale.ordinal()
.range(colorRange);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(innerRadius);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d;
});
svg.selectAll('.arc').remove();
var g = svg.selectAll('.arc')
.data(pie(data))
.enter().append('g')
.attr('class', 'arc');
g.append('path')
.attr('d', arc)
.style('fill', function(d, i) {
return color(i);
})
.style('stroke', 'none');
// .style('transform', 'rotate(-' + rotateAngle + 'deg)') // Centers the highlighted arc at 90 degrees
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment