d3js精通教程_d3js从基础到精通第二部分
d3js精通教程
In the last article we learned about fundamentals of D3js such as selections, DOM Manipulation, SVG, Scales and data binding. If you are getting started with D3js, I highly recommend reading that article first and then come back here.
在上一篇文章中,我們了解了D3js的基礎知識,例如選擇,DOM操作,SVG,Scales和數(shù)據(jù)綁定。 如果您開始使用D3js,我強烈建議您先閱讀該文章 ,然后再回到這里。
Lets dive into the world of Interactivity, Data Manipulation and Layouts in this article.
在本文中,我們將深入探討“ 交互性” ,“ 數(shù)據(jù)處理和布局 ”領域。
事件處理 (Event Handling)
Events can be attached by calling .on(event, function) on selection element and by passing the type of listener.
可以通過在選擇元素上調(diào)用.on(event, function)并傳遞偵聽器的類型來附加.on(event, function) 。
Lets start with the most basic interactive functionalities.
讓我們從最基本的交互功能開始。
演示地址
In the above example, click on js tab. See what are all the event handlers attached on the circles. Reload page and open console by pressing F12 and click on “Run Pen”.circles.on(‘mouseover’, console.log) this console logs all the parameters passed to callback functions. circles.on(‘mouseover’, (event, data)=> {}) 1st Event details, 2nd bond Data. This event is used is get the current event details which can used for variety of things like drag and drop and zoom. Alternatively, you can directly access event in js like this circles.on(‘click’, () => console.log(“Event”, event)) circles.on(‘dblclick’, ondblClick) : On double click event, here in the example we passed a function which turns the element “red”.circles.on(‘wheel’, (d, i, n) => console.log(“weeeee”, i)) : On scroll event, which is very handy for user friendly zooming event and last example ondrag event which is bit different where we have to call d3.drag() function on the element. Which has its on events like start, drag, end.
在上面的示例中,單擊js選項卡。 查看圓上附加的所有事件處理程序。 重新加載頁面并按F12打開控制臺,然后單擊“運行筆”。 circles.on('mouseover', console.log)此控制臺記錄傳遞給回調(diào)函數(shù)的所有參數(shù)。 circles.on('mouseover', (event, data)=> {})第一事件詳細信息,第二債券數(shù)據(jù)。 使用此event是獲取當前事件的詳細信息,該事件的詳細信息可用于拖放和縮放之類的各種操作。 另外,您也可以直接在js中訪問event ,例如circles.on('click', () => console.log(“Event”, event)) circles.on('dblclick', ondblClick) :發(fā)生雙擊事件時,在此示例中,我們傳遞了一個將元素變?yōu)椤凹t色”的函數(shù)。 circles.on('wheel', (d, i, n) => console.log(“weeeee”, i)) :滾動事件,對于用戶友好的縮放事件和最后一個示例ondrag事件非常方便不同之處在于我們必須在元素上調(diào)用d3.drag()函數(shù)。 它具有on事件,例如start , drag , end 。
circles.call(d3.drag().on(“start”, console.log)
.on(“drag”, onDrag)
.on(“end”, console.log))
In onDrag function we select the element and change its cx property with x property from its event .
在onDrag函數(shù)中,我們選擇元素并從其event x屬性更改其cx屬性。
function onDrag(d,i,n) {d3.select(this).attr(“cx”, event.x)
}
Remember only traditional function passes context in this while arrow function refers to its relative parent context. If its an arrow function it should look like.
請記住,只有傳統(tǒng)function會在this傳遞上下文,而箭頭函數(shù)是指其相對父上下文。 如果它具有箭頭功能,則應該看起來像。
const onDrag = (d,i,n) => {d3.select(n[i]).attr(“cx”, event.x)
}
Here is the list of most used mouse events.
這是最常用的鼠標事件的列表。
click: Mouse click on the element.
click :鼠標單擊元素。
dblclick: Mouse double click on the element.
dblclick :鼠標雙擊元素。
contextmenu: Mouse right click on the element.
contextmenu :鼠標右鍵單擊元素。
mouseenter: Mouse enters the element.
mouseenter :鼠標進入元素。
mouseleave: Mouse leaves the element.
mouseleave :鼠標離開元素。
mousemove: Mouse movement over the element.
mousemove :鼠標在元素上移動。
mouseout: Mouse leaves the element or any of its children.
mouseout :鼠標離開該元素或其任何子元素。
mouseover: Mouse enters the element or any of its children.
mouseover :鼠標進入元素或其任何子元素。
for Touch interface read Here
對于觸摸界面,請點擊此處
Check more about it here.
在這里查看更多信息。
There are more D3js provided interactive features
D3js提供了更多的交互式功能
d3.drag: Drag event with mouse.
d3.drag :用鼠標拖動事件。
d3.zoom: Zoom event with mouse wheel.
d3.zoom :使用鼠標滾輪縮放事件。
d3.brush: Can be used for select area or zooming.
d3.brush :可用于選擇區(qū)域或縮放。
d3.force : To simulate gravitational animation
d3.force :模擬重力動畫
Follow me Sai Kiran Goud to learn about these interactive visualization developments.
跟隨我Sai Kiran Goud了解這些交互式可視化技術的發(fā)展。
工具提示示例: (Tooltip Example:)
https://codepen.io/krngd2/pen/YzqYNRe
https://codepen.io/krngd2/pen/YzqYNRe
數(shù)據(jù)處理 (Data Manipulation)
D3js comes with variety of data manipulation function which comes in pretty handy while dealing with any kind off data.
D3js帶有各種數(shù)據(jù)處理功能,在處理任何類型的數(shù)據(jù)時都非常方便。
Take some example data of Covid-19 cases in India.
以印度的Covid-19病例為例。
[{“dailyconfirmed”: “78168”,”dailydeceased”: “892”,
”dailyrecovered”: “62145”,
”date”: “01 September “,
”totalconfirmed”: “3766121”,
”totaldeceased”: “66337”,
”totalrecovered”: “2899515”},
.......
......
.....
{“dailyconfirmed”: “90600”,
”dailydeceased”: “916”,
”dailyrecovered”: “73161”,
”date”: “05 September “,
”totalconfirmed”: “4110852”,
”totaldeceased”: “70095”,
”totalrecovered”: “3177666”}]
This is an array of Objects, If we want to get the maximum dailyconfirmed cases, you have d3.max(data, accessor) , example
這是一個對象數(shù)組,如果要獲取最大的dailyconfirmed病例,則可以使用d3.max(data, accessor) ,例如
d3.max(data,(p)=> p["dailyconfirmed"] ) // returns "90600"Similarly we have
同樣,我們有
最高 (Max)
d3.max(iterable[, accessor]) : returns max valued3.maxIndex(iterable[, accessor]) : returns Index of max valued3.greatest(iterable[, comparator]) : returns object of max index
d3.max( iterable [, accessor ]) :返回最大值d3.maxIndex( iterable [, accessor ]) :返回最大值的索引d3.greatest( iterable [, comparator ]) :返回最大索引的對象
敏 (Min)
d3.min(iterable[, accessor]) : returns min valued3.minIndex(iterable[, accessor]) : returns Index of min valued3.least(iterable[, comparator]) : returns object of min index
d3.min( iterable [, accessor ]) :返回最小值d3.minIndex( iterable [, accessor ]) :返回最小值d3.least( iterable [, comparator ])的索引:返回min索引的對象
其他 (Others)
d3.sum(iterable[, accessor]) : returns Sumd3.extent(iterable) : returns [min, max] combined in an arrayd3.mean(iterable[, accessor]) : returns mean valued3.median(iterable[, accessor]) : returns median value
d3.sum( iterable [, accessor ]) :返回總和d3.extent( iterable) :返回[min,max]組合成一個數(shù)組 d3.mean( iterable [, accessor ]) : 返回平均值 d3.median( iterable [, accessor ]) : 返回中值
轉型 (Transformation)
Here the interesting part begins. Transformation methods comes very handy when you want to modify your data to desired format. Lets learn about most used transformation methods.Taken above data as example.
從有趣的部分開始。 當您想將數(shù)據(jù)修改為所需格式時,轉換方法非常方便。 讓我們了解最常用的轉換方法。以上述數(shù)據(jù)為例。
d3.group(data, d => d["date"])output
輸出
This returns a Map with key of date and value of the rest of the values. This comes handy when you want to access values by passing the date and using Map instead Object for such data improves performance too. You can pass more callback functions to get more nested data. Convert to Array using Array.from(mapData) .
這將返回一個地圖 帶有日期的鍵和其余值的值。 當您想通過傳遞日期并使用Map代替Object訪問此類數(shù)據(jù)來訪問值時,這也很方便。 您可以傳遞更多的回調(diào)函數(shù)以獲取更多的嵌套數(shù)據(jù)。 使用轉換為數(shù)組 Array.from(mapData) 。
Note keys should be unique, otherwise they will be over ridden. If you want an error to be thrown, use d3.index(iterable, keyAccessory) with similar functionality. If you want to customized output of values array use d3.rollup(iterable, reduce, …keys) // Learn about .reduce() here You can check more about it Here.
注意鍵應該是唯一的,否則它們將被覆蓋。 如果要引發(fā)錯誤,請使用 d3.index(iterable, keyAccessory) 具有相似的功能。 如果你想要將其值陣列中使用的定制輸出d3.rollup( iterable , reduce , …keys ) // Learn about .reduce() here你可以查看更多關于它在這里 。
d3.range([start, ]stop[, step]) // generates array of valuesd3.merge([[1], [2, 3]]) //returns [1, 2, 3]d3.pairs([1, 2, 3, 4]); // returns [[1, 2], [2, 3], [3, 4]]d3.shuffle(array[, start[, stop]]) // shuffles the array
d3.range([ start , ] stop [, step ]) // generates array of valuesd3.merge([[1], [2, 3]]) //returns [1, 2, 3]d3.pairs([1, 2, 3, 4]); // returns [[1, 2], [2, 3], [3, 4]]d3.shuffle( array [, start [, stop ]]) // shuffles the array
d3.ticks(start, stop, count)// returns array of equal interval rounded values
// example
d3.ticks(1, 10, 5)
// returns
Here I only listed out mostly used methods according my experience. You can read about all of them here Statistics, Search, Transform
在這里,我僅根據(jù)我的經(jīng)驗列出最常用的方法。 您可以在此處閱讀所有內(nèi)容的統(tǒng)計信息 , 搜索 , 轉換
版面 (Layouts)
There are so many types of visualization. D3 gives us some handy inbuilt visualizations like Packed Circles, TreeMap, Network Graph etc.
可視化類型很多。 D3為我們提供了一些方便的內(nèi)置可視化效果,例如填充圓圈,TreeMap,網(wǎng)絡圖等。
In-order to develop them you need to understand an important data manipulation method to produce Hierarchical Data.
為了開發(fā)它們,您需要了解一種重要的數(shù)據(jù)處理方法以生成分層數(shù)據(jù)。
Hierarchical Data
分層數(shù)據(jù)
Just like how Scales takes data and outputs the positional points, Hierarchical functions, takes hierarchical data and adds positional x,y and other points such that it can produces certain layout. We need to prepare some hierarchical data first. For that we have d3.stratify() .Lets say we have data something like
就像Scales如何獲取數(shù)據(jù)并輸出位置點一樣,Herarchical函數(shù)也可以獲取層次數(shù)據(jù)并添加位置x,y和其他點,從而可以生成特定的布局。 我們需要首先準備一些分層數(shù)據(jù)。 為此,我們有d3.stratify()讓我們說我們有類似的數(shù)據(jù)
const data = [{"name": "Eve", "parent": ""},
{"name": "Cain", "parent": "Eve"},
{"name": "Seth", "parent": "Eve"},
{"name": "Enos", "parent": "Seth"},
{"name": "Noam", "parent": "Seth"},
{"name": "Abel", "parent": "Eve"},
{"name": "Awan", "parent": "Eve"},
{"name": "Enoch", "parent": "Awan"},
{"name": "Azura", "parent": "Eve"}
]
To convert this into hierarchical data we need pass this data to d3.stratify()
要將其轉換為分層數(shù)據(jù),我們需要將此數(shù)據(jù)傳遞給d3.stratify()
const hierarchicalDataGenrator = d3.stratify().id(d => d.name)
.parentId(d => d.parent)
hierarchicalDataGenrator(data)Output輸出量
Above is output, we get Hierarchical data object with we can get hierarchicalDataGenrator.ancestors() , hierarchicalDataGenrator.descendants() , hierarchicalDataGenrator.leaves() . Typically you don’t need to use these directly. Let build some visualizations now.
以上是輸出,我們得到了Hierarchical數(shù)據(jù)對象,并獲得了hierarchicalDataGenrator.ancestors() , hierarchicalDataGenrator.descendants() , hierarchicalDataGenrator.leaves() 。 通常,您不需要直接使用它們。 現(xiàn)在建立一些可視化。
實心圓 (Packed Circles)
https://covidwithd3js.kiran.dev/worldbubble/https://covidwithd3js.kiran.dev/worldbubble/Lets take a simple same data as above but add an extra point value. Value is the percentage of circle occupation under its parent. Lets keep everything 1. Like this {“name”: “Eve”, “parent”: “”, value: 1} .
讓我們采用與上述相同的簡單數(shù)據(jù),但添加一個額外的點值。 值是其父項下的圈子職業(yè)百分比。 讓我們保留所有內(nèi)容1.像這樣{“name”: “Eve”, “parent”: “”, value: 1} 。
Make Data Hierarchical
使數(shù)據(jù)分層
.id(d=>d.name)
.parentId(d => d.parent)
const hData = hDataGenerator(data)
2. Sum the value
2.求和
hData.sum(d => d.value)console.log(
You can see extra value key added. That’s the sum of all its children values.
您會看到添加了value鍵。 那是所有子代價值的總和。
3. Prepare the pack layout
3.準備包裝布局
const packLayout = d3.pack().size([400, 400]);
packLayout(hData)
4. Use it to create layout
4.用它來創(chuàng)建布局
const nodes = d3.select('svg').append('g')
.selectAll('circle')
.data(hData.descendants())
.enter()
.append("g")nodes.append('circle')
.attr('cx', (d) => d.x)
.attr('cy', (d) => d.y)
.attr('r', (d) => d.r)
.style("stroke", "black")
.style("fill", "none")nodes.append('text')
.attr('y', (d) => d.y - d.r + 16)
.attr('x', (d) => d.x)
.text(d => d.data.name)
Output
輸出量
樹狀圖 (TreeMap)
Almost everything same as above but instead of d3.pack() we use d3.tree()
幾乎一切都與上面相同,但不是d3.pack()我們使用d3.tree()
Prepare Layout
準備布局
const treeLayout = d3.tree().size([400, 400]);treeLayout(hData)
Create
創(chuàng)造
const svg = d3.select('svg')//circlessvg.append('g')
.selectAll('circle.node')
.data(hData.descendants())
.enter()
.append('circle')
.classed('node', true)
.attr('cx', (d) => d.x)
.attr('cy', (d) => d.y)
.attr('r', 4);// Links
svg.append("g")
.selectAll('line.link')
.data(hData.links())
.enter()
.append('line')
.attr('x1', (d) => d.source.x)
.attr('y1', (d) => d.source.y)
.attr('x2', (d) => d.target.x)
.attr('y2', (d) => d.target.y)
.style('stroke', 'black')
Output
輸出量
Learn More about Hierarchy here
在此處了解有關層次結構的更多信息
I am hoping by now you got pretty good idea about how to play around with D3js. I know we haven't built any exciting chart in these series. In my next article we will build Racing Bar chart. So follow me for the more exciting stuff.
我希望到目前為止,您對如何使用D3js有一個很好的了解。 我知道在這些系列中我們還沒有建立任何令人興奮的圖表。 在我的下一篇文章中,我們將構建賽車條形圖。 因此,請跟隨我獲得更精彩的內(nèi)容。
翻譯自: https://medium.com/analytics-vidhya/d3js-basic-to-mastery-part-2-mastery-680db40f2ec5
d3js精通教程
總結
以上是生活随笔為你收集整理的d3js精通教程_d3js从基础到精通第二部分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VMware虚拟机安装Centos 8系
- 下一篇: 如何查看CentOS操作系统版本