在第一个附加的d3元素上没有解析数据

时间:2015-10-17 08:49:25

标签: javascript d3.js

我在D3.js中很新,并且有这个简单的代码,See jsbin output here

var data = [
  {country: 'Kenya', performance_rate: 5},
  {country: 'Uganda', performance_rate: 5},
  {country: 'Rwanda', performance_rate: 2},
  {country: 'S.Sudan', performance_rate: 1}
];

var chartBody = d3.select('body').append('h1').text('Progress by country');

var chart = d3.selectAll('p');

chart.data(data).enter().append('span')
 .classed('bar',true).style('width', function(d){
   rate = (d.performance_rate *100)/5;
   return rate+'%';}).text(function(d){
   return d.country;
});

我正在尝试从数据集创建一个简单的条形图。我的问题是,数据集中的第一项,即{ country: Kenya, performance_rate: 5}未在输出中传递。

如何确保正确呈现所有数据集项目。

1 个答案:

答案 0 :(得分:2)

问题出在你的html中,你已经有了一个p元素,所以当你执行d3.selectAll('p');时,它会返回一个现有元素。

  

<强> selection.enter()

     

返回输入选择:每个数据元素的占位符节点   在其中找到对应的现有DOM元素   目前的选择。

因此从html中删除p元素并尝试如下所示。

var chart = d3.select('body').append('p').selectAll("span");

工作代码段

var data = [
  {country: 'Kenya', performance_rate: 5},
    {country: 'Uganda', performance_rate: 5},
    {country: 'Rwanda', performance_rate: 2},
    {country: 'S.Sudan', performance_rate: 1}
];
var chartBody = d3.select('body').append('h1').text('Progress by country');

var chart = d3.select('body').append('p').selectAll("span");

chart.data(data).enter().append('span').classed('bar', true).style('width', function(d){
  rate = (d.performance_rate *100)/5;
  return rate+'%';
}).text(function(d){
  return d.country;
});
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3 bar chart learning">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .bar {
      background-color: yellow;
      height: 21px;
      padding: 10px;
      color: black;
      display:block;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
</body>
</html>