d3.js更新条形图时遇到麻烦

时间:2019-04-03 03:06:53

标签: javascript arrays d3.js nested

我正在尝试制作一个条形图,该条形图使用json文件中的数据进行循环更新,但是由于数组内部嵌套了一个数组,因此我无法访问数据JSON数据

//X Scale
var x = d3.scaleBand()
    .domain(['Black', 'Hispanic', 'Other', 'White'])
    .range([0, width])
    .padding(0.2);

//Y Scale
var y = d3.scaleLinear()
    .domain([0, 120000])
    .range([height, 0]);

//X Axis
var xAxisCall = d3.axisBottom(x);
g.append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0,' + height + ')')
    .call(xAxisCall);

//Y axis
var yAxisCall = d3.axisLeft(y)
    .tickFormat(function(d){return '$' + d; })
g.append('g')
    .attr('class', 'y axis')
    .call(yAxisCall);

//Bars
var rects = g.selectAll('rect')
    .data(data[0])
    var groupOne = data[0];


//Problem is below
    console.log(groupOne.standings[0]);
    rects.enter()
        .append('rect')
            .**attr('y', function(d){return y(data[0].standings); })
            .attr('x', function(d){return x(d.standings) })
            .attr('width', function(d){return height - y(data[0].standings);})**
            .attr('width', x.bandwidth)
            .attr('fill', 'grey');


//Here is a sample of the json data
[
  {
    "standings": [
      {
      "Black": 36815,
      "Hispanic": 39742,
      "Other": 58884,
      "White": 86229
    }
    ],
    "year": "1989"
  },

我的条形图应显示条形图上列出的排名值,最终使我可以每年更新图表。

1 个答案:

答案 0 :(得分:0)

您的代码段并未关闭所有括号,但似乎data [0]是一个数组项,该对象是具有两个属性,即standing和year的对象。因此,在您的示例中引用36815号,您的引用是data [0] .standings [0] .Black。同时,您对1989年的参考是data [0] .year

相关问题