score:1

Accepted answer

What you can do is use a for/forEach for your data dataByCLIN and create rects inside each loop like this:

var bars = svg.selectAll('.rects');
dataByCLIN.forEach(function(d,i1) {
  bars.data(d.values).enter().append('rect').attr('class', 'rects')
    .attr('width', function(d) {
      return d.cost;
    })
    .attr('height', 10)
    .attr('y', function(d, i) {
      return (i+i1+i1+1) * 20 - 20;
    });
});

Here's a fiddle:

var json = [{
    "CLIN": "1",
    "cost": 257,
  },
  {
    "CLIN": "1",
    "cost": 846,
  },
  {
    "CLIN": "2",
    "cost": 162

  },
  {
    "CLIN": "2",
    "cost": 984
  }
];


var margin = {
  top: 20,
  right: 160,
  bottom: 35,
  left: 30
};

var width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var svg = d3.select('body')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)
  .append('g')
  .attr('transform', 'translate(' + margin.left + "," + margin.top + ")");

var dataByCLIN = d3.nest()
  .key(function(d) {
    return d.CLIN;
  })
  .entries(json);

var bars = svg.selectAll('.rects');
dataByCLIN.forEach(function(d, i1) {
  bars.data(d.values).enter().append('rect').attr('class', 'rects')
    .attr('width', function(d) {
      return d.cost;
    })
    .attr('height', 10)
    .attr('y', function(d, i) {
      return (i + i1 + i1 + 1) * 20 - 20;
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


Related Query