Eric
Eric

Reputation: 133

Create d3 linear color legend using d3 colors

I want to create color legend using linear gradient > https://bl.ocks.org/HarryStevens/6eb89487fc99ad016723b901cbd57fde . But how can I pass my d3 colors here because its in the form like d3.scaleSequential(d3.interpolateViridis).domain([0,1]). In linear gradient the colors are passed as below :

var data = [{"color":"#000004","value":0},{"color":"#02020c","value":5}]

linearGradient.selectAll("stop")
.data(data)
.enter().append("stop")
.attr("offset", d => ((d.value - extent[0]) / (extent[1] - extent[0]) * 100) + "%")
.attr("stop-color", d => d.color);

Note: My dataset is like below:

export const colorScales: Record<string, (num: number) => string> = {
Rainbow: d3.interpolateHslLong("red", "blue"),
Spectral: d3.interpolateSpectral,
RdYlBu: d3.interpolateRdYlBu,
RdYlGn: d3.interpolateRdYlGn,
RdBu: d3.interpolateRdBu,
PiYG: d3.interpolatePiYG,
Warm: d3.interpolateWarm,
Cool: d3.interpolateCool,
Viridis: d3.interpolateViridis,
Inferno: d3.interpolateInferno,
Magma: d3.interpolateMagma,
Plasma: d3.interpolatePlasma,
CubeHelix: d3.interpolateCubehelixDefault,
YlOrRd: d3.interpolateYlOrRd,
Blues: d3.interpolateBlues,
};

Upvotes: 1

Views: 1645

Answers (1)

SmokeyShakers
SmokeyShakers

Reputation: 3412

Here's an example using d3.interpolateSpectral. You can create your data with d3.range and map:

// create an array of steps based on the color scale
var data = d3.range(10).map(d=> ({color:d3.interpolateSpectral(d/10), value:d}))
// get the array's min and max value
var extent = d3.extent(data, d => d.value); 

linearGradient.selectAll("stop")
.data(data)
.enter().append("stop")
.attr("offset", d => ((d.value - extent[0]) / (extent[1] - extent[0]) * 100) + "%")
.attr("stop-color", d => d.color);

Technically you could do it with colors from those categorical schemes, but it doesn't make much sense to me.

 // d3.schemeCategory10 is just an array of color
 // use map to add some values (index in this case)

var data = d3.schemeCategory10.map((d,i) => ({color:d, value:i}))

linearGradient.selectAll("stop")
    .data(data)
    .enter().append("stop")
    .attr("offset", d => d.value/9 * 100) + "%") // index/length
    .attr("stop-color", d => d.color);

Upvotes: 1

Related Questions