跳至內容

閾值比例尺

閾值比例尺類似於 量化比例尺,但允許您將網域中的任意子集對應到範圍中的離散值。輸入網域仍然是連續的,並根據一組閾值劃分為切片。請參閱 此分級地圖 以取得範例。

scaleThreshold(domain, range)

範例 · 原始碼 · 使用指定的 domainrange 建立新的閾值比例尺。

js
const color = d3.scaleThreshold([0, 1], ["red", "white", "blue"]);

如果未指定 domain,則預設為 [0.5]。

js
const color = d3.scaleThreshold(["red", "blue"]);
color(0); // "red"
color(1); // "blue"

如果未指定 range,則預設為 [0, 1]。

threshold(value)

範例 · 原始碼 · 給定輸入 網域 中的 value,傳回輸出 範圍 中對應的值。例如

js
const color = d3.scaleThreshold([0, 1], ["red", "white", "green"]);
color(-1); // "red"
color(0); // "white"
color(0.5); // "white"
color(1); // "green"
color(1000); // "green"

threshold.invertExtent(value)

原始碼 · 傳回 網域 [x0, x1] 中的值範圍,對應於 範圍 中的,表示從範圍到網域的反向對應。

js
const color = d3.scaleThreshold([0, 1], ["red", "white", "green"]);
color.invertExtent("red"); // [undefined, 0]
color.invertExtent("white"); // [0, 1]
color.invertExtent("green"); // [1, undefined]

此方法對互動很有用,例如用來判斷滑鼠下方的像素位置對應於網域中的哪個值。低於最低閾值的範圍是未定義的(未受約束),高於最高閾值的範圍也是如此。

threshold.domain(domain)

範例 · 原始碼 · 如果指定了 domain,將比例尺的網域設定為指定的值陣列。

js
const color = d3.scaleThreshold(["red", "white", "green"]).domain([0, 1]);

這些值必須是遞增順序,否則比例尺的行為將是未定義的。這些值通常是數字,但任何自然排序的值(例如字串)都可以使用;閾值比例尺可用於編碼任何已排序的類型。如果比例尺範圍中的值數為 n + 1,則比例尺網域中的值數必須為 n。如果網域中的元素少於 n,則範圍中的其他值將被忽略。如果網域中的元素多於 n,則比例尺可能會對某些輸入傳回未定義。

如果未指定 domain,則傳回比例尺目前的網域。

js
color.domain() // [0, 1]

threshold.range(range)

範例 · 原始碼 · 如果指定了 range,將比例尺的範圍設定為指定的值陣列。

js
const color = d3.scaleThreshold().range(["red", "white", "green"]);

如果比例尺網域中的值數為 n,則比例尺範圍中的值數必須為 n + 1。如果範圍中的元素少於 n + 1,則比例尺可能會對某些輸入傳回未定義。如果範圍中的元素多於 n + 1,則其他值將被忽略。給定陣列中的元素不必是數字;任何值或類型都可以使用。

如果未指定 range,則傳回比例尺目前的範圍。

js
color.range() // ["red", "white", "green"]

threshold.copy()

範例 · 原始碼 · 傳回此比例尺的精確副本。

js
const c1 = d3.scaleThreshold(d3.schemeBlues[5]);
const c2 = c1.copy();

對此比例尺的變更不會影響傳回的比例尺,反之亦然。