javascript - 第一个附加 d3 元素上未解析任何数据

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

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

最佳答案

问题出在您的 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/

相关文章:

javascript - 如果 li 为空,则在 jQuery 中隐藏 excluding span 属性

javascript - 在 Lambda 的索引名称中包含日志组名称

javascript - 将空文件发送到服务器 React-Native

javascript - Ember transitionTo 路由模型钩子(Hook)未调用

javascript - 在javascript中转换为分层数组

javascript - 不确定是否调用了 d3.json 中的回调

d3.js - 如何在 d3 中为路径及其点设置动画

javascript - 在 Bootstrap 选项卡中显示单个 bxslider

javascript - D3 多层时间轴

javascript - 如何将文本 append 到 SVG