当前位置: 首页 > 工具软件 > Per.js > 使用案例 >

js/d3.min.js_在5分钟内学习D3.js

王锐
2023-12-01

js/d3.min.js

by Sohaib Nehal

通过Sohaib Nehal

在5分钟内学习D3.js (Learn D3.js in 5 minutes)

创建数据可视表示的简介 (An introduction to creating visual representations of your data)

D3.js is a JavaScript library used to manipulate documents based on data. It uses HTML, CSS, and SVG to create visual representations of data which can be viewed on any modern browser.

D3.js是一个JavaScript库,用于根据数据处理文档。 它使用HTML,CSS和SVG创建可以在任何现代浏览器上查看的数据的可视表示形式。

It also provides some awesome features for interactions and animations.

它还为交互和动画提供了一些很棒的功能。

In this tutorial, we will explore the basic concepts and features of D3.js. We’ll learn how to use it with the help of few examples like rendering a bar chart, rendering HTML and SVG elements, and applying transformations and events to them.

在本教程中,我们将探讨D3.js的基本概念和功能。 我们将在几个示例的帮助下学习如何使用它,例如渲染条形图,渲染HTML和SVG元素以及对其应用转换和事件。

We’ve also created a free 10-part course on D3.js on Scrimba. Check it out here.

我们还在Scrimba上的D3.js上创建了免费的10部分课程。 在这里查看。

D3入门 (Getting started with D3)

As D3.js is a JavaScript library, you can simply include it in your HTML file inside a script tag.

由于D3.js是JavaScript库,因此您只需将其包含在HTML文件中的script标签内即可。

<script src='https://d3js.org/d3.v4.min.js'><;/script>

The full source and tests are also available for download on GitHub.

完整的源代码和测试也可以在GitHub上下载

DOM选择 (DOM Selection)

Using D3.js, we can manipulate the Document Object Model (DOM), meaning we can select elements and apply various transformations on them.

使用D3.js,我们可以操作文档对象模型(DOM),这意味着我们可以选择元素并对其进行各种转换。

Let’s start off with a simple example, where we’ll be using D3 to select and change the color and the font size of a heading tag.

让我们从一个简单的示例开始,在该示例中,我们将使用D3选择和更改标题标记的颜色和字体大小。

<html><head>    <title>Learn D3 in 5 minutes</title></head><body><h3>Today is a beautiful day!!</h3><script src='https://d3js.org/d3.v4.min.js'></script><script>    d3.select('h3').style('color', 'darkblue');    d3.select('h3').style('font-size', '24px');</script>
</body></html>

So we’re simply chaining the select() method on the d3 object, and then following up with style(). The first parameter dictates what we want to change and the second gives the value. Here’s the result:

因此,我们只是在d3对象上链接select()方法,然后跟进style() 。 第一个参数指示我们要更改的内容,第二个参数给出值。 结果如下:

数据绑定 (Data Binding)

The next concept you’ll need to learn is data binding, as that’s one of the coolest features of D3. Using it, we can populate or manipulate DOM elements in real-time.

您需要学习的下一个概念是数据绑定,因为这是D3最酷的功能之一。 使用它,我们可以实时填充或操作DOM元素。

In our HTML, we have a simple unordered list <ul>:

在我们HTML中,我们有一个简单的无序列表< ul>:

<ul> </ul>

We want to create the list elements using a data object. Here’s the code for doing exactly that:

我们要使用数据对象创建列表元素。 这是执行此操作的代码:

<script>    var fruits = ['apple', 'mango', 'banana', 'orange'];    d3.select('ul')        .selectAll('li')        .data(fruits)        .enter()        .append('li')        .text(function(d) { return d; });</script>

In our JavaScript code above, D3 first selects the <ul> and any <li>elements inside it using select() and selectAll() methods. It might seem a bit weird that we’re selecting all li elements before we’ve created them, but that’s just how D3 works.

在上面JavaScript代码,D3首先选择< UL>的d an ý<LI>元素INSI de it us荷兰国际集团小号elect() and全选()方法。 这似乎有点不可思议,我们是SE le电视机之前,我们已经创造了他们,但是这D3是如何工作的所有li元素。

We then pass in the data with the data() method, and add enter(), which works kind of like a loop. Everything after this point will be executed once per item in the fruits array.

然后,我们使用data()方法传入数据,并添加enter() ,其工作方式类似于循环。 此后的所有操作将对fruits数组中的每个项目执行一次。

In other words, it then appends an<li>for every item in data. For every <li>tag, it also appends text inside it using the text() method. The parameter d inside the text() callback function refers to the element in the array at the given iteration (apple, mango, and so on).

换句话说,它随后为数据中的每个项目附加一个< li>。 对于ever ÿ<LI>标记时,它也追加我内部文本t usin克text()方法。 钍e参数d insid e是文本()回调函数指的是阵列中的元件在给定的迭代(苹果,莽 O,等等)。

So here’s our final result:

所以这是我们的最终结果:

创建SVG元素 (Creating SVG Elements)

Scalable Vector Graphics (SVG) is a way to render graphical elements and images in the DOM. As SVG is vector-based, it’s both lightweight and scalable. D3 uses SVG to create all its visuals, and therefore it is a core building block of the library.

可伸缩矢量图形(SVG)是一种在DOM中呈现图形元素和图像的方法。 由于SVG基于矢量,因此既轻巧又可扩展。 D3使用SVG来创建其所有视觉效果,因此它是库的核心构建块。

Here in the example below, a rectangle is being drawn using D3 in an SVG container.

在下面的示例中,此处是使用SVG容器中的D3绘制的矩形。

//Select SVG elementvar svg = d3.select('svg');
//Create rectangle element inside SVGsvg.append('rect')   .attr('x', 50)   .attr('y', 50)   .attr('width', 200)   .attr('height', 100)   .attr('fill', 'green');

In this code, D3 is rendering a rectangle element inside the DOM. It first selects the SVG element and then renders a rectangle element inside it. It also sets x and y coordinates of the rectangle along with its width, height, and fill properties using the attr() method.

在此代码中,D3正在DOM中渲染一个矩形元素。 它首先选择SVG元素,然后在其中渲染一个矩形元素。 它还使用attr()方法设置矩形的x和y坐标以及其宽度,高度和填充属性。

创建条形图 (Creating a Bar Chart)

D3 also lets us create a lot of different types of charts and graphs to represent data in efficient ways. In the example below, we are creating a simple bar chart using D3.

D3还使我们可以创建许多不同类型的图表,以有效的方式表示数据。 在下面的示例中,我们使用D3创建一个简单的条形图。

Let’s start out by creating an SVG tag directly in our HTML.

让我们从直接在HTML中创建SVG标签开始。

<svg width='200' height='500'></svg>

Then, we’ll write the JavaScript we need in order to render the bar chart in our <svg> tag:

然后,我们将编写所需JavaScript,以便在<s vg>标签中呈现条形图:

var data = [80, 120, 60, 150, 200];
var barHeight = 20;
var bar = d3.select('svg')          .selectAll('rect')          .data(data)          .enter()          .append('rect')          .attr('width', function(d) {  return d; })          .attr('height', barHeight - 1)          .attr('transform', function(d, i) {            return "translate(0," + i * barHeight + ")";          });

In this code, we have an array of numbers which we will use to render our bar chart. Each item in an array would represent a single bar. We make use of the fact that bars are just rectangles with variable width or height.

在这段代码中,我们有一组数字,这些数字将用于渲染条形图。 数组中的每个项目都代表一个条。 我们利用以下事实:条形图只是宽度或高度可变的矩形。

After selecting the SVG and rectangle elements, we pass our dataset using the data() method and call enter() to start looping on data.

选择SVG和矩形元素后,我们使用data()方法传递数据集,并调用enter()开始循环数据。

For each data item, we render a rectangle and set its width equivalent to its value. We then set the height of each bar, and to avoid overlapping, we provide some padding to it by subtracting 1 from barHeight.

对于每个数据项,我们渲染一个矩形并将其宽度设置为其值。 然后,我们设置每个条形的高度,为避免重叠,我们通过从barHeight减去1来barHeight提供填充。

We then transform our bars using the translate property which will position every rectangle one after another rather than starting from the same point. transform() takes a callback function which gets data and index in its parameters. We translate the rectangle on the y-axis, by multiplying index with the height of the bar.

然后,我们使用translate属性转换条形,该属性将使每个矩形一个接一个地定位,而不是从同一点开始。 transform()一个回调函数,该函数获取其参数中的数据和索引。 我们通过将索引乘以条形的高度来平移y轴上的矩形。

Here’s the result:

结果如下:

事件处理 (Event Handling)

Finally, let’s also look at event handling. D3 also supports built-in and custom events which we can bind to any DOM element with its listener. In the example below, we are binding the click event to the button and appending a heading tag to a body in its event handler.

最后,让我们看一下事件处理。 D3还支持内置事件和自定义事件,我们可以使用其侦听器将其绑定到任何DOM元素。 在下面的示例中,我们将click事件绑定到按钮,并将标题标签附加到其事件处理程序中的主体。

d3.select('#btn')        .on('click', function () {            d3.select('body')               .append('h3')               .text('Today is a beautiful day!!');        });

So when we click the button, the text below appears:

因此,当我们单击按钮时,将显示以下文本:

结论 (Conclusion)

D3.js is a very powerful, yet simple, JavaScript library that allows you to play with and bring life to documents based on data using HTML, CSS, and SVG.

D3.js是一个非常强大而又简单JavaScript库,可让您使用HTML,CSS和SVG来基于数据玩转文档并赋予其生命。

There are a lot of good resources available online to learn D3.js. There is a free course on D3.js which we have created on Scrimba and is available for free here.

在线上有很多不错的资源可用于学习D3.js。 我们在Scrimba上创建了有关D3.js的免费课程,可在此处免费获得

Thank you :)

谢谢 :)

I am Sohaib Nehal. I am a Full-Stack Web Application Developer. You can reach me at sohaib.nehal@ymail.com or on Twitter @Sohaib_Nehal. Thank you :-)

我是Sohaib Nehal。 我是全栈Web应用程序开发人员。 您可以通过sohaib.nehal@ymail.com或通过Twitter @Sohaib_Nehal与我联系。 谢谢 :-)

翻译自: https://www.freecodecamp.org/news/learn-d3-js-in-5-minutes-c5ec29fb0725/

js/d3.min.js

 类似资料: