2015-10-17 67 views
0

上没有数据,我在D3.js非常新的,有这个简单的代码,See jsbin output here解析的第一附加D3元素

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})未在输出中传递。

如何确保我所有的数据集项目都能正确呈现。

回答

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>

+0

感谢Gilsha。我已经看到你在那里做了什么。很棒。 –

+0

很高兴帮助:) – Gilsha

+0

不同的事情,但是,你如何附加上面的代码,我可以运行它。我的意思是“> Run code snippet”和底部的其他按钮。我想在将来做这样的事情。什么是工具?再次感谢。 –