javascript - 在 d3 的同一 JSON 文件中使用多个数据集

标签 javascript json d3.js nvd3.js

我正在尝试修改 Line Plus Bar chart来自 nvd3,这样当单击按钮时,图表将切换到一周中不同日期(周日至周六)的数据。

现在我很难让它显示一周中某一天的数据;由于某种原因,它会显示一周中的所有天。这是我的代码:

d3.json("employee_data.json",function(error,data) {
  if(error) return console.warn(error);
  nv.addGraph(function() {
      var chart = nv.models.linePlusBarChart()
            .margin({top: 30, right: 60, bottom: 50, left: 70})
            //We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
            .x(function(d,i) {
              console.log(i)
              return i })
            .y(function(d,i) {
              return d[1] })
            ;

      chart.xAxis.tickFormat(function(d,i) {
        var dx = data[0].values[i] && data[0].values[i][0] || 0;
        return 'Sun' + dx
      });

      chart.y1Axis
          .tickFormat(d3.format(',f'));

      chart.y2Axis
          .tickFormat(function(d) { return d3.format(',f')(d) });

      chart.bars.forceY([0]);

      d3.select('#chart svg')
        .datum(data)
        .transition()
        .duration(0)
        .call(chart);

      nv.utils.windowResize(chart.update);

      return chart;
  });

});

JSON 的设置方式类似于:

[
  {
    "key" : "Sun_Employees",
    "bar" : true,
    "color" : "#ccf",
    "values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
  },
  {
    "key": "Sun_Tasks",
    "color" : "#333",
    "values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
  },
  {
    "key" : "Mon_Employees",
    "bar" : true,
    "color" : "#ccf",
    "values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
  },
  {
    "key": "Mon_Tasks",
    "color" : "#333",
    "values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
  }
}

我认为这个问题与 .x(function(d,i) { return i}) 行有关,但不知道如何限制它。

最佳答案

在将数据绑定(bind)到您的选择之前尝试过滤数据。这看起来像:

var filteredData = data.filter(function(d) { return d.key.startsWith("Sun"); });
d3.select('#chart svg')
  .datum(filteredData)
  ...

关于javascript - 在 d3 的同一 JSON 文件中使用多个数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34291867/

相关文章:

javascript - 在提示框中输入密码类型

javascript - 使用 intvall 和 page_refresh 将数据重新加载到网页中

java - 如何使用 GSON Streaming 避免将整个 JSON 加载到内存中?

ios - 在 Swift 4 中从 uitextfields 将数据发布到服务器

d3.js - 将 D3 Band Zoom 从 v3 升级到 v4

javascript - 可以push到数组所在的数组吗

javascript - 从 LocalStorage 中的 ng-repeat 中编辑对象的属性

javascript - 从 JSON 对象获取字符串

javascript - 使用 D3.js 为折线图中的线条设置动画

javascript - d3js 图像中心或侧面/底部/顶部的力定向路径