简体   繁体   English

使用 d3 colors 创建 d3 线性颜色图例

[英]Create d3 linear color legend using d3 colors

I want to create color legend using linear gradient > https://bl.ocks.org/HarryStevens/6eb89487fc99ad016723b901cbd57fde .我想使用线性渐变 > 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]).但是我怎样才能在这里传递我的 d3 colors,因为它的形式类似于 d3.scaleSequential(d3.interpolateViridis).domain([0,1])。 In linear gradient the colors are passed as below:在线性梯度中,colors 传递如下:

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,
};

Here's an example using d3.interpolateSpectral .这是一个使用d3.interpolateSpectral的示例。 You can create your data with d3.range and map :您可以使用d3.rangemap创建数据:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM