0

I'm new to D3 so please be patient.

I am trying to build a side by side graph in d3.js. I'm a little stuck trying to add 'rect' (rectangle svg) inside of 'g' (groups). I'm not sure if the json data is formated incorrectly. Or if I am missing some fundamental step.

Json object = data;

var data = [
 {
  dontknow: 3,
  neutral: 0,
  optimistic: 62,
  pessimistic: 15,
  veryoptimistic: 14,
  verypessimistic: 6,
  year: 2013
 },
 {
  dontknow: 10,
  neutral: 4,
  optimistic: 42,
  pessimistic: 55,
  veryoptimistic: 64,
  verypessimistic: 5,
  year: 2013
 }
]

And my code looks like this:

var svg = d3.select("#graph5")
.append("svg")
.attr("width", w)
.attr("height", h);

//Create groups
var g = svg.selectAll('g')
.data(data)
.enter()
.append('g');

//Add rectangles to each g
var rect = g.selectAll("rect")
   .data(function(d){ return d })
   .enter()
   .append("rect")
   .attr('width', function(d){ d.year });

The SVG and 'g' elements appear to be created correctly and correct data is associated with the 'g' but the final rect call doesnt seem to work.

Any ideas?

Thanks

MichaelBell
  • 890
  • 1
  • 10
  • 24

1 Answers1

0

Looks like the object keys were causing an issue. By utilising the inbuild 'd3.values(d)' function I was able to create the rects.

Here is the code (Notice the second line difference):

var rect = g.selectAll("rect")
 .data(function(d){ return d3.values(d) })
 .enter()
 .append("rect")
 .attr('width', function(d,i){ console.log(d); return d });
MichaelBell
  • 890
  • 1
  • 10
  • 24