javascript - D3 : skip null values in line graph with several lines

标签 javascript d3.js

我有一个动态数组来显示包含多条线的折线图。示例:

var data = 
[[{x:2005, y:100}, {x:2007, y:96.5}, {x:2009, y:100.3}, {x:2011, y:102.3}], 
 [{x:2005, y:100}, {x:2007, y:105},  {x:2009, y:102},   {x:2011, y:104}]]

我脚本的这一部分将画线:

graph.selectAll("path.line")
.data(data)
.enter().append("path")
.attr("class", "line")
.style("stroke", function(d, i) { return d3.rgb(z(i)); })
.style("stroke-width", 2)
.attr("d", d3.svg.line()
.y(function(d) { return y(d.y); })
.x(function(d,i) { return x(i); }));

(我使用的脚本是基于 http://cgit.drupalcode.org/d3/tree/libraries/d3.linegraph/linegraph.js )

我的问题:数据数组是动态的,我事先不知道里面有什么。有时 2005 年的 y 值将为空:

var data = 
[[{x:2005, y:100},  {x:2007, y:96.5}, {x:2009, y:100.3}, {x:2011, y:102.3}], 
 [{x:2005, y:null}, {x:2007, y:105},  {x:2009, y:102},   {x:2011, y:104}]]

如何让第二行忽略第一个对象,并从 2007 年开始?

根据答案 1,这就是我现在所拥有的,仍然显示整行:

data = 
[[{x:2005, y:100},  {x:2007, y:96.5}, {x:2009, y:100.3}, {x:2011, y:102.3}], 
 [{x:2005, y:null}, {x:2007, y:105},  {x:2009, y:102},   {x:2011, y:104}]];

var validatedInput = function(inptArray) { 
 return inptArray.filter(function(obj) {
  return obj.y != null;
 });
};

graph.selectAll("path.line")
    .data(data, validatedInput)
  .enter().append("path")
    .attr("class", "line")
    .style("stroke", function(d, i) { return d3.rgb(z(i)); })
    .style("stroke-width", 2)
    .attr("d", d3.svg.line()
    .y(function(d) { return y(d.y); })
    .x(function(d,i) { return x(i); }));

最佳答案

最后我自己解决了这个问题,基于解决方案here .诀窍是尽可能晚地删除空值,以便保留 Canvas 上所有值(点)的位置。

graph.selectAll("path.line")
    .data(data)
  .enter().append("path")
    .attr("class", "line")
    .style("stroke", function(d, i) { return d3.rgb(z(i)); })
    .style("stroke-width", 2)
    .attr("d", d3.svg.line()
    .y(function(d) { return y(d.y); })
    .defined(function(d) { return d.y; }) // Omit empty values.
    .x(function(d,i) { return x(i); }));

这将适用于行首和行尾的空值。

关于javascript - D3 : skip null values in line graph with several lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24855630/

相关文章:

javascript - 将 D3 力图转换为 v4

javascript - d3 : color a line based on another dataset

javascript - 在 HTML 页面上显示 SVG

javascript - 从 ASP 代码隐藏调用外部 Javascript 函数

javascript - 使用 jquery .load() 函数获取包含句点 ('.' 的参数的 404 错误

javascript - 谷歌浏览器在打印预览中不显示图像

javascript - 如何从 D3.js 中的嵌套访问值?

javascript - 如何访问在 d3.json 请求之外声明的变量

Javascript 输入数字

javascript - 如果第二个对象数组具有相同的值,则将数组添加到对象数组内的对象