当前位置:网站首页>[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
2022-06-13 02:33:00 【The winter holiday of falling marks】
d3.js Introductory tutorial 1-d3 Basic knowledge of
List of articles
d3.js It is a tool for drawing JavaScript library . It can visualize any type of data . This document shows several interactive examples , Illustrates the d3.js Key concepts of , Thus, the first basic scatter diagram is generated .
1 HTML Introduce
1.1 What is? HTML?
HTML Introduce :
- HTML Stands for hypertext markup language . Basically , It is the language behind any website .Mozilla or Safari etc. Web The browser will read such files and translate them into the web page
- stay HTML In file , The elements that make up the web page are created , And described by the label . for example , Level 1 The title of is given by h1 The label indicates , Paragraphs with labels , from p The label represents the image img
- without html Basic knowledge of , It is impossible to learn d3.js
<!DOCTYPE html>
<!-- Add the title -->
<h1>First html document</h1>
<!-- Add a line of text -->
<p>This is my first sentence</p>
<!-- Add links -->
<p>This is <a href="https://www.d3-graph-gallery.com">a link to the d3 graph gallery</a></p>
First html document
This is my first sentence
This is a link to the d3 graph gallery
Copy and paste the above code into your local file . be called test.html, Build a simple web page .
1.2 Custom document styles CSS
CSS Represents a cascading style sheet , It allows specific styles to be applied to use html Created elements .
<!DOCTYPE html>
<!-- Apply a specific style to inGreen Class elements -->
<style>
.inRed { color: red; }
.inFont { font-size: 20px}
</style>
<!-- Add the title , And add corresponding classes -->
<h1 class="inFont">First html document</h1>
<!-- Add a line of text -->
<p class="inRed">This is my first sentence</p>
<!-- Add links -->
<p>This is <a href="https://www.d3-graph-gallery.com">a link to the d3 graph gallery</a></p>
First html document
This is my first sentence
This is a link to the d3 graph gallery
1.3 structure svg graphics
- svg Represents scalable vector graphics . It is a vector image format . Basically , It is a language that allows you to build shapes using code
- d3.js The chart is actually a set of svg Combined shapes
- d3.js Showing different shapes of svg
<!DOCTYPE html>
<!-- Add the title -->
<h1>First html document</h1>
<!-- Add a line of text -->
<p>This is my first sentence</p>
<!-- add to svg shape -->
<svg>
<circle style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>
First html document
This is my first sentence
2 d3 Introduction to drawing
2.1 Use Javascript and d3.js Modifying elements
JavaScript It is one of the three core technologies of the front end . It realizes the interactivity of web pages .d3.js It's a javascript library , Especially useful for data visualization . It allows the creation of 、 Select and modify elements . In the following example , d3 Used to select the target circle and modify its stroke-width. Although it is not very impressive , But we will use the same procedure to set the position of hundreds of circles and get a scatter plot .
<h1>First html document</h1>
<!-- Add the title -->
<p>This is my first sentence</p>
<!-- add to svg shape -->
<svg>
<circle class="target" style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>
<!-- load d3 -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3
.select(".target") // choice target class
.style("stroke-width", 8) // modify svg Graphic outline
.style("opacity", 0.5) // modify svg Graphic transparency
</script>
2.2 Console.log()
Browser running Html,css and Javascript And display the result as a web page , If something goes wrong , A notification will be sent in the browser console , You can right-click the page to open -> Check ->console, Open console , Or press directly F1. For example, enter... In the console ,console.log(“sometext”), You can print sometext character string .
2.3 Coordinate system
structure d3.js The chart starts by creating a svg Elements . This element has width and height Two parameters to control the size , In pixels . The coordinates of the upper left corner are x=0 and y=0, The coordinates of the lower left corner x=0 and y=height, The coordinates in the upper right corner x=width and height=0, It is the same as the common picture coordinate representation . The code that displays the three circles is as follows :
<!-- Add an empty svg picture -->
<svg id="dataviz_area" height=200 width=450></svg>
<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
var svg = d3.select("#dataviz_area")
// Add circle ,cx and cy Is the coordinates of the center of the circle ,r As the radius of
svg.append("circle")
.attr("cx", 2).attr("cy", 2).attr("r", 40).style("fill", "blue");
svg.append("circle")
.attr("cx", 120).attr("cy", 70).attr("r", 40).style("fill", "red");
svg.append("circle")
.attr("cx", 300).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>
2.4 scale
If you want to express it as a percentage svg The location of the elements in , Then you need to use a scale , A scale bar is a function that converts a range of pixel values into a position percentage . It is called scale. If my data is percentage and my svg The area is 400px Width . that 0% representative 0px,100% representative 400 Pixels .50% representative 200 Pixels . The scale has domain and range Two attributes ,range Set the range of pixel values ,domain Set position percentage .
<!-- Add an empty svg picture -->
<svg id="viz_area" height=200 width=450></svg>
<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
// choice svg Drawing area
var svg = d3.select("#viz_area")
// Create scale bar
// take 0 To 400 Pixels are mapped to 0% To 100%
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, 400]);
// Try console.log(x(25)) To see x Purpose of function .
// Set picture size in percentage
svg.append("circle")
.attr("cx", x(10)).attr("cy", 100).attr("r", 40).style("fill", "blue");
svg.append("circle")
.attr("cx", x(50)).attr("cy", 100).attr("r", 40).style("fill", "red");
svg.append("circle")
.attr("cx", x(100)).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>
2.5 Add axis
d3 Provides some functions for automatically drawing axes . These axes are always related to the scale scale Corresponding .axisBottom() Create a horizontal axis , With scale and label at the bottom .axisLeft() Will be used for Y Axis .
<!-- Add an empty svg picture -->
<svg id="viz_area" height=200 width=450></svg>
<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
// choice svg Drawing area
var svg = d3.select("#viz_area")
// Create scale bar
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, 400]);
// Displays the axis corresponding to this scale
svg.call(d3.axisBottom(x));
// Set picture size in percentage
svg.append("circle")
.attr("cx", x(10)).attr("cy", 100).attr("r", 40).style("fill", "blue");
svg.append("circle")
.attr("cx", x(50)).attr("cy", 100).attr("r", 40).style("fill", "red");
svg.append("circle")
.attr("cx", x(100)).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>
2.6 Margins and offsets
The shaft position often needs to be adjusted , for example ,X The axis is usually at the bottom of the chart . This is due to translation function , application .attr(“transform”, “translate(20,50)”) To an element , Translate it to the right 20 Pixels , Pan to the bottom 50 Pixels .
<!-- Add an empty svg picture -->
<div id="Area"></div>
<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
// Set the size and margin of the drawing
var margin = { top: 10, right: 40, bottom: 30, left: 30 },
width = 450 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// take svg Object attached to the body of the page
var svg = d3.select("#Area")
.append("svg")
// Leave blank
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g") // Add ruler
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Pan image
// establish x Axis scale
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, width]);
svg.append('g')
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// establish y Axis scale
var y = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
svg.append('g')
.call(d3.axisLeft(y));
</script>
2.7 Data binding
Bind data to svg Element is the last step we need to complete the scatter diagram . in my opinion , This is also the most difficult part to understand . It always follows the same steps :
- svg: Select the... Where the chart is located svg Area
- .selectAll(“whatever”): Select all elements that have not been created , I know it's strange .
- .data(data): Specify the data to use .
- .enter(): Start data cycle . The following code will apply to data[0],data[1] And so on .
- .append(“circle”): For each iteration , Add a circle .
- .attr(“cx”, function(d){ return x(d.x) }): Given circle x Location . here d It will be data[0], then data[1] wait .
<!-- Add an empty svg picture -->
<div id="scatter_area"></div>
<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>
// Set the size and margin of the drawing
var margin = { top: 10, right: 40, bottom: 30, left: 30 },
width = 450 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// take svg Object attached to the body of the page
var svG = d3.select("#scatter_area")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Create data
var data = [{ x: 10, y: 20 }, { x: 40, y: 90 }, { x: 80, y: 50 }]
// establish x Axis scale
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, width]);
svG.append('g')
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// establish y Axis scale
var y = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
svG.append('g')
.call(d3.axisLeft(y));
// Add data
svG.selectAll("whatever")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d.x) })
.attr("cy", function (d) { return y(d.y) })
.attr("r", 7)
</script>
3 Reference resources
边栏推荐
- Restrict cell input type and display format in CXGRID control
- Queuing theory, game theory, analytic hierarchy process
- 01 初识微信小程序
- ROS learning-6 detailed explanation of publisher programming syntax
- About the fact that I gave up the course of "Guyue private room course ROS manipulator development from introduction to actual combat" halfway
- 4.11 introduction to firmware image package
- GMM Gaussian mixture model
- OpenCVSharpSample04WinForms
- (novice to) detailed tutorial on machine / in-depth learning with colab from scratch
- After idea uses c3p0 connection pool to connect to SQL database, database content cannot be displayed
猜你喜欢
Priority queue with dynamically changing priority
Graph theory, tree based concept
Leetcode 926. Flip string to monotonically increasing [prefix and]
Flow chart of interrupt process
03 认识第一个view组件
I didn't expect that the index occupies several times as much space as the data MySQL queries the space occupied by each table in the database, and the space occupied by data and indexes. It is used i
Classification and summary of system registers in aarch64 architecture of armv8/arnv9
[reading paper] generate confrontation network Gan
拍拍贷母公司信也季报图解:营收24亿 净利5.3亿同比降10%
How can intelligent safe power distribution devices reduce the occurrence of electrical fire accidents?
随机推荐
Thinking back from the eight queens' question
Basic exercise of test questions Yanghui triangle (two-dimensional array and shallow copy)
redis
[reading point paper] deeplobv3 rethinking atlas revolution for semantic image segmentation ASPP
redis 多个服务器共用一个
Leetcode 926. 将字符串翻转到单调递增 [前缀和]
Paipai loan parent company Xinye quarterly report diagram: revenue of RMB 2.4 billion, net profit of RMB 530million, a year-on-year decrease of 10%
Automatic differential reference
Opencv 10 brightness contrast adjustment
Paper reading - beat tracking by dynamic programming
OpenCVSharpSample05Wpf
【LeetCode-SQL】1532. Last three orders
Priority queue with dynamically changing priority
Understand CRF
Classification and summary of system registers in aarch64 architecture of armv8/arnv9
Opencv 17 face recognition
[reading papers] dcgan, the combination of generating countermeasure network and deep convolution
Microsoft Pinyin opens U / V input mode
(novice to) detailed tutorial on machine / in-depth learning with colab from scratch
ROS learning -5 how function packs with the same name work (workspace coverage)