Color Gradient on Line

Learn how to apply a color gradient to the lines of your graph.

Applying a color gradient to a line based on value

I know that we were impressed with the changing dots in a scatter plot based on the value. But could we go one better?

How about we try to reproduce the same effect but by varying the colour of the plotted line. This is a neat feature and a useful example of the flexibility of D3.js and SVG in general.

Here is a plotted line that is red below 400, green above 620, and black in between.

How cool is that?

Enough beating around the bush, how is the magic line produced?

Starting with our simple line graph, there are only two blocks of code to go in. One is CSS in the <style> area, and the second is a tricky little piece of code that deals with gradients.

CSS

First, the CSS.

Press + to interact
.line {
fill: none;
stroke: url(#line-gradient);
stroke-width: 2px;
}

This block will go in the <style> area.

There’s the fairly standard fill of none and a stroke width of 2 pixels, but the ...