Search code examples
d3.jsdc.jscrossfilter

dc.js: expense tracker, show distribution for each month in a pie chart


I'm trying to make a Pie chart that shows each months expenses on different category.Like,when I give January ,the slices should display Grocery,fuel,rent etc.How can I make it with this data?

code

function show_monthly_exp_distribution(ndx) {
    var dim = ndx.dimension(dc.pluck('Month'));
    var group = dim.group().reduceCount(dc.pluck());

    dc.pieChart("#exp-pie")
      .height(300)
      .width(800)
      .radius(70)
      .transitionDuration(1000)
      .dimension(dim)
      .group(group)
      .legend(dc.legend().gap(7));
  }

csv data

Month,Utility Bills,Groceries,Dining Out,Fuel,Rent,totalexp
January,100,500,100,90,1000,1400
February,120,450,50,120,1000,1740
March,130,550,120,60,1000,1860
April,100,300,80,150,1000,1630
May,90,600,75,80,1000,1845
June,130,560,150,90,1100,2030
July,70,610,120,100,1100,2000
August,120,459,100,80,1100,1859
September,140,432,80,90,1100,1842
October,60,456,110,110,1100,1836
November,80,487,60,180,1200,2007
December,150,390,210,100,1200,2050

Solution

  • As Gordon suggested, start by changing the format of your data so you have only one datapoint per row. If you can't change the data on the csv, you can do it in js (code not tested, might work directly... or not ;)

    var data = [];
    var type = "Utility Bills,Groceries,Dining Out,Fuel,Rent".split(",");
    d3.csv("yourcsv", function(d) {
      type.forEach(function(c){
        data.push({month:d.month,type:c,amount:+d[c]});
      });
      return null; //doesn't matter what you return, discard the initial csv anyway)
    }).then (function(dummy){
       ndx=crossfilter(data);      
    });
    

    Once you have done that, you can easily have one graph to filter the month (or selectMenu graph) and your pieChart