2015-10-17 64 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」和底部的其他按鈕。我想在將來做這樣的事情。什麼是工具?再次感謝。 –