Reputation: 89
consider the jsfiddle link http://jsfiddle.net/5D5eD/5/. It has data values [2,2],[3,3],[4,4], [5, 4],[5.5, 5],[6, 6],[6, 7],[5,6]. Here in this example the last two values are [6,7] and [5,6]. I want to add a condition i.e if y value is lesser than previous value then the datapoint should increment the y value by 1 unit. In my case the line from [6,7] to [5,6] should be replaced by a line from [6,7] to [5,8]. How to achieve this in the code ?
var line = d3.svg.line()
.x(function(d){return x(d[0]);})
.y(function(d){return y(d[1]);})
.interpolate("linear");
g.append("path")
.attr("d", function(d) { return line(data)})
.attr("transform", "translate(0,0)")
.style("stroke-width", 2)
.style("stroke", "steelblue")
.style("fill", "none");
// end of drawing lines
main.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat(""))
main.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""))
function make_x_axis() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(30)
}
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(17)
}
Upvotes: 3
Views: 3160
Reputation: 5015
Please see this FIDDLE. I think this is what you want.
var py;
data.map(
function(d) {
if (d[1] < py)
d[1] = py + 1;
py = d[1];
}
);
Upvotes: 1
Reputation: 8858
Don't know more efficient method than this but it met your requirement.
Use condition in returning y
axis values in both drawing circle and lines using :
(i>0 && d[1]<data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); (where i is index from function(d, i) { ... })
Two lines changed in following:
// Drawing circles
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d, i) { return x(d[0]); })
.attr("cy", function (d, i) { return (i>0 && d[1]<data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); })
.attr("r", 5)
.style("fill", function (d) { return color(d[0]);}) ;
// begin of drawing lines
var line = d3.svg.line()
.x(function(d){return x(d[0]);})
.y(function(d, i){ return (i>0 && d[1]<data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); })
.interpolate("linear");
Upvotes: 0