D3:在具有几行的线图中跳过空值 [英] D3: skip null values in line graph with several lines

查看:141
本文介绍了D3:在具有几行的线图中跳过空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态数组来显示一个包含几行的线图。示例:

I have a dynamic array to show a line graph with several lines. Example:

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}]]

我的脚本的这部分将绘制线:

This part of my script will draw the lines:

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值为null:

My problem: the data array is dynamic, I don't know beforehand what's in it. Sometimes the y value for 2005 will be null:

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年开始?

How can I make the second line ignore the first object, and start at 2007?

基于回答1这是我的现在仍然显示整行:

Based on answer 1 this is what I have now, still showing the whole line:

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); }));


推荐答案

最后我自己解决了,解决方案此处。诀窍是尽可能晚地删除空值,因此画布上所有值(点)的位置都会保留。

In the end I solved this myself, based on the solution here. The trick is to remove the empty values as late as possible, so the positions of all values (points) on the canvas are preserved.

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); }));

这将适用于行开头和结尾处的空值。

This will work for empty values at the start and end of a line.

这篇关于D3:在具有几行的线图中跳过空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆