D3.js method of realizing histogram _javascript skills

Source: Internet
Author: User
Tags script tag in domain

D3.js Introduction

D3.js is a JavaScript library based on data manipulation documents. D3 helps you to bring energy to your data by using HTML, SVG, and CSS. D3 values Web standards to provide you with the full functionality of modern browsers, rather than giving you a proprietary framework. Combines powerful visual components and data-driven DOM operations. You can also see that it is using SVG to render the chart, so using d3.js requires a certain SVG base.

How do I use d3.js to achieve a histogram?

The histogram has axes and columns inside. However, we also need an SVG canvas to draw these things. First put the approximate drawing frame together, the code is as follows (please note that at this point I added the D3.js script tag to the body tag.) Then we can use the D3 method later:

 <! DOCTYPE html>  
 

The implementation of the axes

To link the real data to the coordinates on the axis on the SVG canvas, we need to define the scale to describe the corresponding relationship. The commonly used scales in D3 have linear and ordinal scales, and their differences are as shown in the figure:

It can be seen from the graph that the corresponding relation of linear scale is continuous, and the corresponding relation of ordinal scale is discrete. To analyze the significance of histogram, we can conclude that the x axis should use ordinal scale, and the Y axis should be linear scale.

//Analog data var DataSet = {x: ["Zhao", "Money", "Sun", "Li", "Zhou", "WU", "Zheng", "Wang"], y: [40, 30, 50, 70, 90, 20
, 10, 40]}; Defines the scale (ordinal scale) of the x axis var XScale = d3.scale.ordinal (). Domain (dataset.x). Rangeroundbands ([0, Width-padding.left-padd
ing.right],0,0); Defines the y-axis scale (linear scale) var Yscale = d3.scale.linear (). Domain ([0, D3.max (DATASET.Y)). Range ([Height-padding.top-paddi
Ng.bottom, 0]);
Define x axis and Y axis var xaxis = D3.svg.axis (). Scale (XScale). Orient (' bottom ');
var yaxis = D3.svg.axis (). Scale (Yscale). Orient (' left '); Add axis element Main.append (' G '). attr (' class ', ' axis '). attr (' transform ', ' translate (0, ' + (Height-padding.bottom-padd
ing.top) + '). Call (Xaxis); Main.append (' G '). attr (' class ', ' axis '). Call (YAxis); 

We simulate some data, each last name corresponds to a number (from here you can also see the ordinal scale of the definition of the domain value is not necessarily a continuous relationship). d3.scale.ordinal()an ordinal scale is created, and the ordinal.domain() definition field of the scale is set, and the domain is ordinal.rangRoundBands() set. Similarly, d3.scale.linear() a linear scale is created, the definition linear.domain() domain is defined, and the Linear.range () defines the range. We then used the d3.svg.axis() two axes we created to apply the scale to them, and we used the direction of the ruler with the axis.orient() axes set. Finally, add the SVG element and use call () to associate the defined axis with the SVG element. Move the elements by setting their transform properties so that they look like a coordinate system.

The following points need to be noted here:

1 ordinal.domain The parameter is an array representing a series of values, and linear.domain the argument is an array of ranges.

2. The nature of the scale is a function that receives values on the defined field to derive the value on the corresponding range.

There is a big difference between an axis with an ordinal scale and a linear scale, which is probably illustrated here.

  rangeRoundBands(interval, padding, outerPadding)The padding and outerpadding are optional, and the default is 0. The code for the scale shown above is like this.

var o = d3.scale.ordinal ()
 . Domain ([0, 1, 2])
 . Rangeroundbands ([0, 100], 0.4, 0.1);

The number of elements in the parameter array in domain is the interval between the number of Rangeband,rangeband padding*step (padding range is 0 to 1), and its relationship to Rangeband is to divide a step evenly, For example, padding is 0.4, the length of Rangeband is 0.6*step. Depending on the code above, the length of the final axis is equal to (0.1 + 2 + 0.6 + 0.1) * Step, which calculates the length of the step, and then the length of the outer spacing, the Rangeband, and the inner spacing. The value scale on the definition field is positioned in the middle of each rangeband. So I got the axes in the schematic (red mark).

Let's draw a histogram and set the style for the axis:

. Axis path,
. Axis line {
 stroke: #000;
 Fill:none;
}

The axis of the resulting histogram is shown in the following illustration:

The realization of the Pillar

The pillars are nothing more than rectangles, which can be painted using RECT elements in SVG. Select the elements of all bar classes under Main (at this point, select an empty set), bind the Dataset.y to this set, and use the number of elements of the array in contrast to the number of enter() SVG elements in the collection, and then automatically complement to the number of the two append() sides equal. Each time the append corresponds to an array element in the Dataset.y. The value is computed using the scale function created earlier and assigned to the X, Y properties of the element being held. The specific code is as follows:

The spacing between rectangles is
var rectmargin = ten;
Add Rectangle
main.selectall ('. Bar ')
  . Data (DATASET.Y).
  Enter ()
  . Append (' rect ').
  attr (' class ', ' Bar ')
  . attr (' x ', function (d, i) {return
   XScale (Dataset.x[i]) + rectmargin;
  })
  . attr (' Y ', function (d, i) {return
   Yscale (d);
  })
  . attr (' width ', xscale.rangeband ()-2*rectmargin)
  . attr (' Height ', function (d, i) {return
   height-padding.top -Padding.bottom-yscale (d);
  })
  . attr (' Fill ', function (d, i) {return
   getcolor (i);
  });

At this point, you get the histogram shown in the following figure.

Summarize

The above is the use of d3.js to achieve the full histogram of the content, interested friends can do their own hands-on practice, so that more conducive to the understanding and learning, I hope this article for everyone's study and work can help. If you have questions you can message exchange, thank you for your support for the cloud Habitat community, small series will be updated on the D3.js article, please continue to pay attention to the cloud habitat community.

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.