D3 Scale functions

来源:https://www.cnblogs.com/kungfupanda/archive/2020/07/18/13334372.html
-Advertisement-
Play Games

https://www.d3indepth.com/scales/ D3 in Depth Home About Introduction to D3 Selections Joins Enter/exit Scales Shapes Layouts Force Geographic Request ...


https://www.d3indepth.com/scales/

D3 in Depth Home About Introduction to D3 Selections Joins Enter/exit Scales Shapes Layouts Force Geographic Requests Transitions Interaction

Scale functions

Scale functions are JavaScript functions that:

  • take an input (usually a number, date or category) and
  • return a value (such as a coordinate, a colour, a length or a radius)

They’re typically used to transform (or ‘map’) data values into visual variables (such as position, length and colour).

For example, suppose we have some data:

[ 0, 2, 3, 5, 7.5, 9, 10 ]

we can create a scale function using:

var myScale = d3.scaleLinear()
  .domain([0, 10])
  .range([0, 600]);

D3 creates a function myScale which accepts input between 0 and 10 (the domain) and maps it to output between 0 and 600 (the range).

We can use myScale to calculate positions based on the data:

myScale(0);   // returns 0
myScale(2);   // returns 120
myScale(3);   // returns 180
...
myScale(10);  // returns 600
View source | Edit in GistRun

Scales are mainly used for transforming data values to visual variables such as position, length and colour.

For example they can transform:

  • data values into lengths between 0 and 500 for a bar chart
  • data values into positions between 0 and 200 for line charts
  • % change data (+4%, +10%, -5% etc.) into a continuous range of colours (with red for negative and green for positive)
  • dates into positions along an x-axis.

Constructing scales

(In this section we’ll just focus on linear scales as these are the most commonly used scale type. We’ll cover other types later on.)

To create a linear scale we use:

var myScale = d3.scaleLinear();
Version 4 uses a different naming convention to v3. We use d3.scaleLinear() in v4 and d3.scale.linear() in v3.

As it stands the above function isn’t very useful so we can configure the input bounds (the domain) as well as the output bounds (the range):

myScale
  .domain([0, 100])
  .range([0, 800]);

Now myScale is a function that accepts input between 0 and 100 and linearly maps it to between 0 and 800.

myScale(0);    // returns 0
myScale(50);   // returns 400
myScale(100);  // returns 800
Try experimenting with scale functions by copying code fragments and pasting them into the console or using a web-based editor such as JS Bin.

D3 scale types

D3 has around 12 different scale types (scaleLinear, scalePow, scaleQuantise, scaleOrdinal etc.) and broadly speaking they can be classified into 3 groups:

We’ll now look at these 3 categories one by one.

Scales with continuous input and continuous output

In this section we cover scale functions that map from a continuous input domain to a continuous output range.

scaleLinear

Linear scales are probably the most commonly used scale type as they are the most suitable scale for transforming data values into positions and lengths. If there’s one scale type to learn about this is the one.

They use a linear function (y = m * x + b) to interpolate across the domain and range.

var linearScale = d3.scaleLinear()
  .domain([0, 10])
  .range([0, 600]);

linearScale(0);   // returns 0
linearScale(5);   // returns 300
linearScale(10);  // returns 600

Typical uses are to transform data values into positions and lengths, so when creating bar charts, line charts (as well as many other chart types) they are the scale to use.

The output range can also be specified as colours:

var linearScale = d3.scaleLinear()
  .domain([0, 10])
  .range(['yellow', 'red']);

linearScale(0);   // returns "rgb(255, 255, 0)"
linearScale(5);   // returns "rgb(255, 128, 0)"
linearScale(10);  // returns "rgb(255, 0, 0)"

This can be useful for visualisations such as choropleth maps, but also consider scaleQuantizescaleQuantile and scaleThreshold.

scalePow

More included for completeness, rather than practical usefulness, the power scale interpolates using a power (y = m * x^k + b) function. The exponent k is set using .exponent():

var powerScale = d3.scalePow()
  .exponent(0.5)
  .domain([0, 100])
  .range([0, 30]);

powerScale(0);   // returns 0
powerScale(50);  // returns 21.21...
powerScale(100); // returns 30

scaleSqrt

The scaleSqrt scale is a special case of the power scale (where k = 0.5) and is useful for sizing circles by area (rather than radius). (When using circle size to represent data, it’s considered better practice to set the area, rather than the radius proportionally to the data.)

var sqrtScale = d3.scaleSqrt()
  .domain([0, 100])
  .range([0, 30]);

sqrtScale(0);   // returns 0
sqrtScale(50);  // returns 21.21...
sqrtScale(100); // returns 30
View source | Edit in GistRun

scaleLog

Log scales interpolate using a log function (y = m * log(x) + b) and can be useful when the data has an exponential nature to it.

var logScale = d3.scaleLog()
  .domain([10, 100000])
  .range([0, 600]);

logScale(10);     // returns 0
logScale(100);    // returns 150
logScale(1000);   // returns 300
logScale(100000); // returns 600
View source | Edit in GistRun

scaleTime

scaleTime is similar to scaleLinear except the domain is expressed as an array of dates. (It’s very useful when dealing with time series data.)

timeScale = d3.scaleTime()
  .domain([new Date(2016, 0, 1), new Date(2017, 0, 1)])
  .range([0, 700]);

timeScale(new Date(2016, 0, 1));   // returns 0
timeScale(new Date(2016, 6, 1));   // returns 348.00...
timeScale(new Date(2017, 0, 1));   // returns 700
View source | Edit in GistRun

scaleSequential

scaleSequential is used for mapping continuous values to an output range determined by a preset (or custom) interpolator. (An interpolator is a function that accepts input between 0 and 1 and outputs an interpolated value between two numbers, colours, strings etc.)

D3 provides a number of preset interpolators including many colour ones. For example we can use d3.interpolateRainbow to create the well known rainbow colour scale:

var sequentialScale = d3.scaleSequential()
  .domain([0, 100])
  .interpolator(d3.interpolateRainbow);

sequentialScale(0);   // returns 'rgb(110, 64, 170)'
sequentialScale(50);  // returns 'rgb(175, 240, 91)'
sequentialScale(100); // returns 'rgb(110, 64, 170)'
View source | Edit in GistRun

Note that the interpolator determines the output range so you don’t need to specify the range yourself.

The example below shows some of the other colour interpolators provided by D3:

View source | Edit in GistRun

There’s also a plug-in d3-scale-chromatic which provides the well known ColorBrewer colour schemes.

Clamping

By default scaleLinearscalePowscaleSqrtscaleLogscaleTime and scaleSequential allow input outside the domain. For example:

var linearScale = d3.scaleLinear()
  .domain([0, 10])
  .range([0, 100]);

linearScale(20);  // returns 200
linearScale(-10); // returns -100

In this instance the scale function uses extrapolation for values outside the domain.

If we’d like the scale function to be restricted to input values inside the domain we can ‘clamp’ the scale function using .clamp():

linearScale.clamp(true);

linearScale(20);  // returns 100
linearScale(-10); // returns 0

We can switch off clamping using .clamp(false).

Nice

If the domain has been computed automatically from real data (e.g. by using d3.extent) the start and end values might not be round figures. This isn’t necessarily a problem, but if using the scale to define an axis, it can look a bit untidy:

var data = [0.243, 0.584, 0.987, 0.153, 0.433];
var extent = d3.extent(data);

var linearScale = d3.scaleLinear()
  .domain(extent)
  .range([0, 100]);
View source | Edit in GistRun

Therefore D3 provides a function .nice() on the scales in this section which will round the domain to ‘nice’ round values:

linearScale.nice();
View source | Edit in GistRun

Note that .nice() must be called each time the domain is updated.

Multiple segments

The domain and range of scaleLinearscalePowscaleSqrtscaleLog and scaleTime usually consists of two values, but if we provide 3 or more values the scale function is subdivided into multiple segments:

var linearScale = d3.scaleLinear()
  .domain([-10, 0, 10])
  .range(['red', '#ddd', 'blue']);

linearScale(-10);  // returns "rgb(255, 0, 0)"
linearScale(0);    // returns "rgb(221, 221, 221)"
linearScale(5);    // returns "rgb(111, 111, 238)"
View source | Edit in GistRun

Typically multiple segments are used for distinguishing between negative and positive values (such as in the example above). We can use as many segments as we like as long as the domain and range are of the same length.

Inversion

The .invert() method allows us to determine a scale function’s input value given an output value (provided the scale function has a numeric domain):

var linearScale = d3.scaleLinear()
  .domain([0, 10])
  .range([0, 100]);

linearScale.invert(50);   // returns 5
linearScale.invert(100);  // returns 10

A common use case is when we want to convert a user’s click along an axis into a domain value:

View source | Edit in GistRun

Scales with continuous input and discrete output

scaleQuantize

scaleQuantize accepts continuous input and outputs a number of discrete quantities defined by the range.

var quantizeScale = d3.scaleQuantize()
  .domain([0, 100])
  .range(['lightblue', 'orange', 'lightgreen', 'pink']);

quantizeScale(10);   // returns 'lightblue'
quantizeScale(30);  // returns 'orange'
quantizeScale(90);  // returns 'pink'

Each range value is mapped to an equal sized chunk in the domain so in the example above:

  • 0 ≤ u < 25 is mapped to ‘lightblue’
  • 25 ≤ u < 50 is mapped to ‘orange’
  • 50 ≤ u < 75 is mapped to ‘lightgreen’
  • 75 ≤ u < 100 is mapped to ‘pink’

where u is the input value.

View source | Edit in GistRun

Note also that input values outside the domain are clamped so in our example quantizeScale(-10) returns ‘lightblue’ and quantizeScale(110) returns ‘pink’.

scaleQuantile

scaleQuantile maps continuous numeric input to discrete values. The domain is defined by an array of numbers:

var myData = [0, 5, 7, 10, 20, 30, 35, 40, 60, 62, 65, 70, 80, 90, 100];

var quantileScale = d3.scaleQuantile()
  .domain(myData)
  .range(['lightblue', 'orange', 'lightgreen']);

quantileScale(0);   // returns 'lightblue'
quantileScale(20);  // returns 'lightblue'
quantileScale(30);  // returns 'orange'
quantileScale(65);  // returns 'lightgreen'
View source | Edit in GistRun

The (sorted) domain array is divided into n equal sized groups where n is the number of range values.

Therefore in the above example the domain array is split into 3 groups where:

  • the first 5 values are mapped to ‘lightblue’
  • the next 5 values to ‘orange’ and
  • the last 5 values to ‘lightgreen’.

The split points of the domain can be accessed using .quantiles():

quantileScale.quantiles();  // returns [26.66..., 63]

If the range contains 4 values quantileScale computes the quartiles of the data. In other words, the lowest 25% of the data is mapped to range[0], the next 25% of the data is mapped to range[1] etc.

scaleThreshold

scaleThreshold maps continuous numeric input to discrete values defined by the range. n-1 domain split points are specified where n is the number of range values.

In the following example we split the domain at 050 and 100

  • u < 0 is mapped to ‘#ccc’
  • 0 ≤ u < 50 to ‘lightblue’
  • 50 ≤ u < 100 to ‘orange’
  • u ≥ 100 to ‘#ccc’

where u is the input value.

var thresholdScale = d3.scaleThreshold()
  .domain([0, 50, 100])
  .range(['#ccc', 'lightblue', 'orange', '#ccc']);

thresholdScale(-10);  // returns '#ccc'
thresholdScale(20);   // returns 'lightblue'
thresholdScale(70);   // returns 'orange'
thresholdScale(110);  // returns '#ccc'
View source | Edit in GistRun

Scales with discrete input and discrete output

scaleOrdinal

scaleOrdinal maps discrete values (specified by an array) to discrete values (also specified by an array). The domain array specifies the possible input values and the range array the output values. The range array will repeat if it’s shorter than the domain array.

var myData = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

var ordinalScale = d3.scaleOrdinal()
  .domain(myData)
  .range(['black', '#ccc', '#ccc']);

ordinalScale('Jan');  // returns 'black';
ordinalScale('Feb');  // returns '#ccc';
ordinalScale('Mar');  // returns '#ccc';
ordinalScale('Apr');  // returns 'black';
View source | Edit in GistRun

By default if a value that’s not in the domain is used as input, the scale will implicitly add the value to the domain:

ordinalScale('Monday');  // returns 'black';

If this isn’t the desired behvaiour we can specify an output value for unknown values using .unknown():

ordinalScale.unknown('Not a month');
ordinalScale('Tuesday'); // returns 'Not a month'

D3 can also provide preset colour schemes (from ColorBrewer):

var ordinalScale = d3.scaleOrdinal()
  .domain(myData)
  .range(d3.schemePaired);
View source | Edit in GistRun

(Note that the Brewer colour schemes are defined within a separate file d3-scale-chromatic.js.)

scaleBand

When creating bar charts scaleBand helps to determine the geometry of the bars, taking into account padding between each bar. The domain is specified as an array of values (one value for each band) and the range as the minimum and maximum extents of the bands (e.g. the total width of the bar chart).

In effect scaleBand will split the range into n bands (where n is the number of values in the domain array) and compute the positions and widths of the bands taking into account any specified padding.

var bandScale = d3.scaleBand()
  .domain(['Mon', 'Tue', 'Wed', 'Thu', 'Fri'])
  .range([0, 200]);

bandScale('Mon'); // returns 0
bandScale('Tue'); // returns 40
bandScale('Fri'); // returns 160

The width of each band can be accessed using .bandwidth():

bandScale.bandwidth();  // returns 40

Two types of padding may be configured:

  • paddingInner which specifies (as a percentage of the band width) the amount of padding between each band
  • paddingOuter which specifies (as a percentage of the band width) the amount of padding before the first band and after the last band

Let’s add some inner padding to the example above:

bandScale.paddingInner(0.05);

bandScale.bandWidth();  // returns 38.38...
bandScale('Mon');       // returns 0
bandScale('Tue');       // returns 40.40...

Putting this all together we can create this bar chart:

View source | Edit in GistRun

scalePoint

scalePoint creates scale functions that map from a discrete set of values to equally spaced points along the specified range:

var pointScale = d3.scalePoint()
  .domain(['Mon', 'Tue', 'Wed', 'Thu', 'Fri'])
  .range([0, 500]);

pointScale('Mon');  // returns 0
pointScale('Tue');  // returns 125
pointScale('Fri');  // returns 500
View source | Edit in GistRun

The distance between the points can be accessed using .step():

pointScale.step();  // returns 125

Outside padding can be specified as the ratio of the padding to point spacing. For example, for the outside padding to be a quarter of the point spacing use a value of 0.25:

pointScale.padding(0.25);

pointScale('Mon');  // returns 27.77...
pointScale.step();  // returns 111.11...

Further reading

ColorBrewer schemes for D3

Mike Bostock on d3-scale


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 主要是用到了after偽類和字體符號。 1 input{ 2 -webkit-appearance: none; 3 -moz-appearance: none; 4 appearance: none; 5 display: inline-block; 6 } 7 input:after{ 8 co ...
  • 1.<video></video> 用於定義視頻,如影視片段 語法<video src="XXXmovie.mp4" controls></video> 支持視頻格式:mp4、ogg移動端、webM高清 常用屬性: src,視頻的地址url autoplay,視頻就緒後自動播放 controls,向 ...
  • 五角星形線的笛卡爾坐標方程式可設為: r=10+(3*sin(θ*2.5))^2 x=r*cos(θ) y=r*sin(θ) (0≤θ≤2π) 根據這個曲線方程,在[0,2π]區間取一系列角度值,根據給定角度值計算對應的各點坐標,然後在計算出的坐標位置繪製一個填充色交替變換的小圓,從而得到沿五角星形 ...
  • 1.新增類型 電子郵件類型,語法<input type="email"/>,input中輸入的內容必須包含“@”,並且“@”後面必須有內容 搜索類型,語法<input type="search"/>,輸入搜索關鍵字的文本框 URL類型,語法<input type="url"/>,輸入web站點的文本 ...
  • 一、安裝node.js(https://nodejs.org/en/) 下載完畢後,可以安裝node,建議不要安裝在系統盤(如C:)。 二、設置nodejs prefix(全局)和cache(緩存)路徑 1、在nodejs安裝路徑下,新建node_global和node_cache兩個文件夾 2、設 ...
  • 1.粒子文本的實現原理 粒子文本的實現原理是:使用兩張 canvas,一張是用戶看不到的canvas1,用來繪製文本;另一張是用戶看到的canvas2,用來根據canvas1中繪製的文本數據來生成粒子。 先在canvas1中用如下的語句繪製待顯示的文本。 ctx1.font = '100px Pin ...
  • 定位 定位:通過定位可以將元素擺放在頁面中任意位置 語法:position屬性設置元素的定位 可選值:static:預設值,開啟定位 relative開啟相對定位 absolute開啟絕對定位 fixed開啟固定定位 相對定位:當元素設置position:relative;開啟元素的相對定位 1 開 ...
  • 背景是這樣的,母親節的時候,我們有個需求就是用戶可以長按或者點擊一個按鈕進行截圖後去分享我們的活動,然而我們的圖片例如頭像,採用又拍雲做 cdn 優化,所以意味著圖片的鏈接跟主頁面所在功能變數名稱不一樣,當需要需要對 canvas 圖片進行 getImageData() 或 toDataURL() 操作的時 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...