D3.js Data-driven Documents

Source: Internet
Author: User

d3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring the data to life using HTML, SVG, and CSS. D3 ' s emphasis on Web standards gives your full capabilities of modern browsers without tying yourself to a proprietary Framework, combining powerful visualization components and a data-driven approach to DOM manipulation.

Download the latest version (3.5.6) here:

    • D3.zip

Or, to link directly to the latest release, copy this snippet:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>

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

#Introduction

Read more tutorials.

D3 allows-bind arbitrary data to a Document Object Model (DOM), and then apply Data-driven transformations to the document. For example, you can use the D3 to generate a HTML table from an array of numbers. Or, use the same data to create a interactive SVG bar chart with smooth transitions and interaction.

D3 is not a monolithic framework, that seeks to provide every conceivable feature. Instead, D3 solves the crux of the problem:efficient manipulation of documents based on data. This avoids proprietary representation and affords extraordinary flexibility, exposing the full capabilities of the Web Standa RDS such as HTML, SVG, and CSS. With minimal overhead, D3 are extremely fast, supporting large datasets and dynamic behaviors for interaction and animation . D3 ' s functional style allows code reuse through a diverse collection of components and plugins.

#Selections

Read more about selections.

modifying documents using the "the website" DOM API is Tedious:the method names is verbose, and the imperative approach requires m Anual iteration and bookkeeping of temporary state. For example, to change the text color of paragraph elements:

var paragraphs = document.getElementsByTagName("p");for (var i = 0; i < paragraphs.length; i++) { var paragraph = paragraphs.item(i); paragraph.style.setProperty("color", "white", null);}

D3 employs a declarative approach, operating on arbitrary sets of nodes called selections. For example, you can rewrite the above loop as:

d3.selectAll("p").style("color", "white");

Yet, you can still manipulate individual nodes as needed:

d3.select("body").style("background-color", "black");

Selectors is defined by the website selectors API and supported natively by modern browsers. Backwards-compatibility for older browsers can is provided by Sizzle. The above examples select nodes by tag name ( "p" "body" and, respectively). Elements may selected using a variety of predicates, including containment, attribute values, class and ID.

D3 provides numerous methods for mutating nodes:setting attributes or styles; Registering event listeners; adding, removing or sorting nodes; and changing HTML or text content. These suffice for the vast majority of needs. Direct access to the underlying DOM was also possible, as each D3 selection was simply an array of nodes.

#Dynamic Properties

Readers familiar with the other DOM frameworks such as JQuery or Prototype should immediately recognize similarities with D3. Yet styles, attributes, and other properties can is specified as functions of data in D3, not just simple Constan Ts. Despite their apparent simplicity, these functions can be surprisingly powerful; d3.geo.paththe function, for example, projects geographic coordinates to SVG path data. D3 provides many built-in reusable functions and function factories, such as graphical primitives for area, line and Pie C Harts.

For example, to randomly color paragraphs:

d3.selectAll("p").style("color", function() { return "hsl(" + Math.random() * 360 + ",100%,50%)";});

To alternate shades of gray for even and odd nodes:

d3.selectAll("p").style("color", function(d, i) { return i % 2 ? "#fff" : "#eee";});

Computed properties often refer to bound data. Data is specified as a array of values, and each value is passed as the first argument (d ) to selection functions. With the default Join-by-index, the first element of the data array is passed to the first node in the selection, the Seco nd element to the second node, and so on. For example, if you bind a array of numbers to paragraph elements, you can use these numbers to compute dynamic font size S:

d3.selectAll("p")    .data([4, 8, 15, 16, 23, 42]) .style("font-size", function(d) { return d + "px"; });

Once the data have been bound to the document, you can omit the data operator; D3 would retrieve the Previously-bound data. This allows Recompute properties without rebinding.

#Enter and Exit

Read more about data joins.

Using D3 ' s enter and exit selections, you can create new nodes for incoming data and remove outgoing nod Es that is no longer needed.

When data was bound to a selection, each element in the data array was paired with the corresponding node in the selection. If There is fewer nodes than data, the extra data elements form the Enter selection, which can instantiate by Appendi Ng to the enter selection. For example:

d3.select("body").selectAll("p")    .data([4, 8, 15, 16, 23, 42]) .enter().append("p") .text(function(d) { return "I’m number " + d + "!"; });

Updating nodes is the default selection-the result of the data operator. Thus, if you forget about the Enter and exit selections, you'll automatically select only the elements for which there E xists corresponding data. A common pattern is to break the initial selection into three parts:the updating nodes to modify, the entering nodes to a DD, and the exiting nodes to remove.

// Update…var p = d3.select("body").selectAll("p")    .data([4, 8, 15, 16, 23, 42]) .text(String);// Enter…p.enter().append("p") .text(String);// Exit…p.exit().remove();

By handling These three cases separately, you specify precisely which operations run on which nodes. This improves performance and offers greater control over transitions. For example, with a bar chart you might initialize entering bars using the old scale, and then transition entering bars to The new scale along with the updating and exiting bars.

D3 lets you transform documents based on data; This includes both creating and destroying elements. D3 allows a existing document in response to user interaction, animation over time, or even asynchronous no Tification from a third-party. A hybrid approach is even possible, where the document was initially rendered on the server, and updated on the client via D3.

#Transformation, not representation

D3 is not a new graphical representation. Unlike processing, Raphaël, or Protovis, the vocabulary of marks comes directly from web standards:html, SVG, and CSS. For example, you can create SVG elements using the D3 and style them with external stylesheets. You can use composite filter effects, dashed strokes and clipping. If Browser vendors introduce new features tomorrow, you'll be able to use them IMMEDIATELY-NO Toolkit update required. And, if you decide on the future to use a toolkit other than D3, you can take your knowledge of standards with you!

Best of all, D3 was easy-to-debug using the browser ' s built-in element inspector:the nodes that you manipulate with D3 are Exactly those that the browser understands natively.

#Transitions

D3 ' s focus on transformation extends naturally to animated transitions. Transitions gradually interpolate styles and attributes over time. Tweening can be controlled via easing functions such as "elastic", "cubic-in-out" and "linear". D3 ' s interpolators support both primitives, such as numbers and numbers embedded within strings (font sizes, path data, etc.), and compound values. You can even extend D3 ' s Interpolator registry to support complex properties and data structures.

For example, to fade the background of the page to black:

d3.select("body").transition()    .style("background-color", "black");

Or, to resize circles in a symbol map with a staggered delay:

d3.selectAll("circle").transition()    .duration(750)    .delay(function(d, i) { return i * 10; }) .attr("r", function(d) { return Math.sqrt(d * scale); });

By modifying only the attributes this actually change, D3 reduces overhead and allows greater graphical complexity in high Frame rates. D3 also allows sequencing of complex transitions via events. And, can still use CSS3 transitions; D3 does not replace the browser's toolbox, but exposes it in a-on-the-it is easier-use.

Want to learn more? Read these tutorials.

Library released under BSD license. Copyright Mike Bostock.

D3.js Data-driven Documents

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.