user3927582
user3927582

Reputation: 189

How to access JSON data with D3.js?

I have an external JSON file structured like so:

{
 data: [
       {
        0: 'cat',
        1: 232,
        2: 45
       },
       {
        0: 'dog',
        1: 21,
        2: 9
       },
       {
        0: 'lion',
        1: 32,
        2: 5
       },
       {
        0: 'elephant',
        1: 9,
        2: 4
       },
       ]
}

Using d3.js I want to access the data with key 2 for the height in a bar chart, so I have set this up:

d3.select('#chart').append('svg')
    .selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('width', barWidth)
    .attr('height', function(d) {
        return d.data['2'];
    });

I can see the SVG canvas but I can't get the rectangles for the bar chart height, any ideas anyone?

Thanks

Upvotes: 0

Views: 1236

Answers (2)

Millie Smith
Millie Smith

Reputation: 4604

I changed a few things to make the code function how a default bar chart would. Your main problem was using d.data instead of d. After that, you have to set the x and y coordinates and an alternating color (or a padding with x) so that the rectangles don't overlap each other.

var width = 30;
var padding = 5;
var chartheight = 100;
d3.select('#chart').append('svg')
  .selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('width', width)
  .attr('height', function(d) {
    return d[2];
  })
  .attr('x', function(d, i) {
    return i*(width + padding);
  })
  .attr('y', function(d, i) {
    return chartheight - d[2];
  });

d3.selectAll('rect')
  .style('fill', function(d, i) {
    return i % 2 == 0 ? "#0f0" : "#00f";
  });

Upvotes: 1

eladcon
eladcon

Reputation: 5825

The d variable sent to your function is already your data, and its called for each item in your array:

.attr('height', function(d) {
    return d['2'];
});

Upvotes: 0

Related Questions