我对 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}
未在输出中传递。
如何确保所有数据集项目均正确呈现。
最佳答案
问题出在您的 html 中,您已经有一个 p 元素,因此当您执行 d3.selectAll('p');
时,它会返回该现有元素。
selection.enter()
Returns the enter selection: placeholder nodes for each data element for which no corresponding existing DOM element was found in the current selection.
因此从 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>
关于javascript - 第一个附加 d3 元素上未解析任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33184669/