I have already put together a post on Sparklines in D3. I was recently asked to put together a sparkline, but to apply the same Viridis color palette that the rest of the graphic uses. The sparkline should look something like this.

Fortunately, this is quite easy to pull off with D3. First, we need to create a gradient.

.attr("x1", "0%")
.attr("x2", "0%")
.attr("y1", "100%")
.attr("y2", "0%");
let stops = [0, 0.25, 0.5, 0.75, 1.0];
.data(stops)
.enter()
.append("stop")
.attr("offset", d => Math.floor(d * 100) + "%")
}

This will produce a gradient definition like the following.

<defs>
<stop offset="0%" stop-color="#440154"></stop>
<stop offset="25%" stop-color="#3b528b"></stop>
<stop offset="50%" stop-color="#21918c"></stop>
<stop offset="75%" stop-color="#5ec962"></stop>
<stop offset="100%" stop-color="#fde725"></stop>
</defs>

To apply this gradient to our sparkline, we reference the id for the path’s stroke property.

.attr("stroke", () => { return options.gradient ? url(#\${gradientId}) : options.style.stroke })

This produces the following SVG HTML element.

<path class="sparkline sparkline-path"
d="..."
fill="none"
stroke-width="1"></path>

If no gradient is given, then the sparkline will fallback to using the given stroke value.

This code is available in Github.