Reputation: 1752
I am trying to plot a path using d3js by reading data from a file. However, there can be NaN values in there too. So, I need a gap in the graph at those points. Say there are 5 points 1,2,3,4,5 and I have values for 1,2,4 and 5 but not 3. So, there should be a path from 1 to 2 and a path from 4 to 5.
I came across a defined accessor for d3.line which does this for line elements. Any ideas as to how can I implement the same with a path.
Thanks in advance
PS: I am trying something like this:
var selection = d3.select(this)
.selectAll('.my-series')
.data(d);
selection.enter()
.append('path');
Upvotes: 0
Views: 783
Reputation: 108512
Still not sure I understand the question, but I've written a code snippet below that demonstrates how to use the defined
accessor of d3.line
. In this code, if either the d.x
or d.y
contain falsy values, d3 will "break-up" the path line segment:
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select('body')
.append('svg')
.attr('width', 200)
.attr('height', 200);
var x = d3.scaleLinear()
.range([0,200])
.domain([1,5]);
var y = d3.scaleLinear()
.range([0,200])
.domain([0, 10]);
var data = [
{
x: 1,
y: Math.random() * 10
},{
x: 2,
y: Math.random() * 10
},{
x: false,
y: false
},{
x: 4,
y: Math.random() * 10
},{
x: 5,
y: Math.random() * 10
}
];
var line = d3.line()
.x(function(d){
return x(d.x);
})
.y(function(d){
return y(d.y);
})
.defined(function(d){
return d.y && d.x;
});
svg.append('path')
.style('stroke', 'steelblue')
.style('stroke-width', 2)
.style('fill', 'none')
.attr('d', line(data));
</script>
</body>
</html>
Upvotes: 2