I am using a d3 line chart that is based off this example: https://codepen.io/louisemoxy/pen/qMvmBM
and am wondering whether I can color this line (also already when the transition is happening) differently depending on the condition y > 0. The data might have multiple values above and below 0, so it's not as easy as splitting the path in 2 pieces.
This is my update method, in which the transition happens:
update(data: Data[]): void {
this.x.domain([new Date(data[0].date), new Date(data[this.data.length - 1].date)])
this.chart.selectAll('.xaxis')
.transition()
.duration(1000)
.call(this.xAxis);
const minVal = d3.min(data, (d: Data) => {return d.val}) as number;
const min = minVal < 0 ? minVal : 0;
const max = d3.max(data, (d: Data) => { return d.val; }) as number;
this.y = d3.scaleLinear()
.domain([min, max])
.range([ this.height, 0 ]);
this.yAxis = d3.axisLeft(this.y);
this.chart.selectAll('.yaxis')
.transition()
.duration(1000)
.call(this.yAxis);
// Create the u variable
let u = this.grp.select("path")
.interrupt()
.datum(data)
.attr('class', 'performance')
.attr('d', d3.line()
.x((d: Data) => { return this.x(new Date(d.date)); })
.y((d: Data) => { return this.y(d.val); }));
const pathLength = u.node().getTotalLength();
const transitionPath = d3
.transition()
.ease(d3.easeSin)
.duration(1500);
u
.attr("stroke-dashoffset", pathLength)
.attr("stroke-dasharray", pathLength)
.attr("stroke", "steelblue")
.transition(transitionPath)
.attr("stroke-dashoffset", 0);
}
As the comments point out the best way to do this is with a
linearGradient. I was going to close this as a duplicate but all the answers I can find don't provide a nice working example. So here's one mixed in with the example code in your link: