Data visualization has always been an important area in the front-end domain. In short, data visualization is to make rigid data vivid by means of graphics, so as to show the information that data wants to express. The chart is the most common means of data visualization, can rely on their own purely manual writing of all kinds of charts is really a headache, all kinds of calculation of all kinds of trouble. That’s all right, let’s open the door to a new world of bar diagrams using D3.js.

D3.jsWhat is?

First, let’s take a look at what d3.js is.

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

Not good English? D3.js is a JavaScript library that helps developers manipulate data-based documents. You can also see here that it renders diagrams in SVG, so using D3.js requires some SVG foundation.

How to do that?

There are axes and columns in the bar chart. However, we also need an SVG canvas to draw these things. To put together the outline of the drawing, please note that I have added the d3.js script tag to the body tag. So we can use D3 method later) :

Container {margin: 30px auto; width: 600px; height: 300px; border: 1px solid #000; }
       
Copy the code

Implementation of coordinate axes

To relate real data to coordinates on the coordinate axes on the SVG canvas, we need to define scales to describe such correspondence. The commonly used scales in D3 include linear scale and ordinal scale, and their differences are shown in the figure:



As can be seen from the figure, the correspondence of linear scale is continuous, while that of ordinal scale is discrete. It can be concluded that ordinal scale should be used for x axis and linear scale should be used for Y axis by analyzing the significance of histogram display.

Simulation data / / var dataset = {x: [" zhao ", "money", "sun", "li", "week", "wu", "zheng", "the king"], y: [30, 40, 50, 70, 90, 20, 10, 40]}. Var xScale = d3.scale.ordinal().domain(dataset.x).rangeroundbands ([0, Width-padding.left-padding. right],0,0); Var yScale = d3.scale.linear().domain([0, d3.max(dataset.y)]) .range([height - padding.top - padding.bottom, 0]); Var xAxis = d3.svg.axis().scale(xScale).orient('bottom'); var yAxis = d3.svg.axis() .scale(yScale) .orient('left'); Main.append ('g').attr('class', 'axis').attr('transform', 'translate(0,' + (height - padding.bottom - padding.top) + ')') .call(xAxis); main.append('g') .attr('class', 'axis') .call(yAxis);Copy the code

We simulated some data, each surname corresponding to a value (from this can also be seen in the ordinal scale of the domain values are not necessarily continuous). D3.scale.ordinal () creates an ordinal scale, while ordinal.domain() sets the scope of the scale, and ordinal.rangroundbands () sets the range. Similarly, d3.scale.Linear () creates a linear scale, linear.domain() defines the domain, and linear.range() defines the range. Next, we create the two axes with d3.svg.axis(), apply the scale to them, and set the orientation of the scale for the axes with axis.orient(). Finally, add an SVG element, using call() to associate the defined axes with the SVG element. Move elements by setting their Transform property to make them look like a coordinate system.

The following points need to be noted:

  • The ordinal.domain argument is an array representing a series of values, while the linear.domain argument is an array representing a range.
  • The essence of a scale is a function that receives values in the domain to derive values in the corresponding range.

The axes on which ordinal scale is applied are quite different from those on linear scale, as outlined here.



The padding and outerPadding in rangeRoundBands(interval, padding, outerPadding) are both optional and default to 0. The code for the scale shown above looks like this.

Var o = d3.scale.ordinal().domain([0, 1, 2]). RangeRoundBands ([0, 100], 0.4, 0.1);Copy the code

Rangebands are separated by a step (padding = 0 to 1). For example, if the padding is 0.4, rangebands are divided evenly by a step. The length of the rangeBand is 0.6*step. According to the above code, the length of the final coordinate axis is equal to (0.1 + 2 + 0.6 + 0.1) * step, from which the length of step can be calculated, and then the length of the outer distance, rangeBand and inner distance can be deduced. The value scale on the domain is positioned in the middle of each rangeBand. This results in the axes in the diagram (highlighted in red).

Let’s draw the bar chart and style the axes:

.axis path,
.axis line {
    stroke: #000;
    fill: none;
}
Copy the code

The coordinate axes of the final bar chart are as follows:

Column implementation

Columns are nothing more than rectangles that can be drawn in SVG using the RECt element. First select all bar elements under main (an empty set is selected at this time), bind dataset. Y to this set, and use Enter () to compare the number of array elements bound to dataset with the number of SVG elements in the set. When used with append(), the number of both sides will be automatically completed to equal. Each append corresponds to an array element in dataset. Y. Use the scale function created earlier to compute the value and assign the x and Y attributes to the holding element. The specific code is as follows:

Var rectMargin = 10; 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); });Copy the code

At this point, the histogram shown in the figure below is obtained.

For complete code and examples, go to bar.html.