在与 d3 的反应中创建函数以将颜色分配给值

Creating functions in react with d3 to assign colors to value

我是 d3 的新手,我一直在阅读他们的文档并查看示例,但没有什么能满足我的需要。 我正在使用反应和打字稿。

我需要创建 2 个函数,其中一个应该如下所示:

mapColor(value, lowerBoundColor, upperBoundColor)
@param value {float} - A decimal float which is between 0 and 1.
@param lowerBoundColor {string} - A hex color code corresponding to a value of 0.
@param upperBoundColor {string} - A hex color code corresponding to a value of 1.
@returns {string} - A hex color code corresponding to the value parameter passed in.

第二个像这样:

linearMap(value, lowerBound, upperBound)
@param value {float} - A decimal float between lowerBound and upperBound.
@param lowerBound {float} - A decimal float which represents the minimum value of the dataset to be clamped.
@param upperBound {float} - A decimal float which represents the maximum value of the dataset to be clamped
@returns {float} - A decimal float between 0 and 1 which corresponds to the value parameter passed in.

这是我目前拥有的:

import React from 'react'
import * as d3 from 'd3'

var data = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,0.9,1]

const mapColor =  d3.scaleLinear()
.domain([0,1])
.range(["f4a261", "264653"])

我如何创建这 2 个函数以响应将来它们可以用作组件的地方。

  1. 有效的十六进制颜色必须以 # 开头。所以范围应该改为 ["#f4a261", "#264653"]。可重用函数应如下所示:
function mapColor(value, lowerBoundColor, upperBoundColor) {
  return d3.scaleLinear()
    .domain([0,1])
    .range([lowerBoundColor, upperBoundColor])(value)
}
function linearMap(value, lowerBound, upperBound) {
  return d3.scaleLinear()
    .domain([lowerBound, upperBound])
    .range([0,1])(value)
}

尽管我认为您应该使用 higher-order 函数来创建它们,如下所示:

function createLinearMap(lowerBound, upperBound) {
  return d3.scaleLinear()
    .domain([lowerBound, upperBound])
    .range([0,1])
}

// Using the HOF
const linearMap = createLinearMap(0, 5)
console.log(linearMap(2)) // 0.4