Search code examples
d3.jschartsradial

Data model for creating a radial bar chart with d3js


I'm trying to make radial bar chart using d3js, but I'm having some trouble with the data model. I have a fiddle here showing what I want to achieve. At the moment the size of the bars are randomly created, but I want to be able to provide my own data (values between 1 and 6) into the chart, but I'm having trouble understanding the data model/structure of d3js, so help would be appreciated!

$(function(){
var $container = $('.chart-container'),
        τ = 2 * Math.PI,
        width = $container.width(),
        height = $container.height(),
        outerRadius = Math.min(width,height)/2.5,
        innerRadius = 10,
        fontSize = (Math.min(width,height)/4);

var dataset = {
  weeks: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
};


var color = d3.scale.ordinal()    .range(['rgb(247,251,255)','rgb(222,235,247)','rgb(198,219,239)','rgb(158,202,225)','rgb(107,174,214)','rgb(66,146,198)','rgb(33,113,181)','rgb(8,81,156)','rgb(8,48,107)']);

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc();

var svg = d3.select('.chart-container').append("svg")
        .attr("width", '100%')
        .attr("height", '100%')
        .attr('viewBox','0 0 '+Math.min(width,height) +' '+Math.min(width,height) )
        .attr('preserveAspectRatio','xMinYMin')
        .append("g")
        .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");

var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g").attr("class", "arc");

var path = gs.selectAll("path")
    .data(function(d) { return pie(d); })
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", function(d, i, j) { return arc.innerRadius(10).outerRadius(20*getRandomInt (1, 6))(d); });
});

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Solution

  • Change your dataset variable and colours here, just pre-populate your required arrays and inject them into D3. i.e. d3.values(dataset)

    var dataset = {
      weeks: [5,10]
    };
    
    var color = d3.scale.ordinal().range(['#ccc','#c33']);