"D3.js Advanced Series-3.0" stack diagram

Source: Internet
Author: User

Stack layout calculates the baseline of each data layer in a two-dimensional array to facilitate the addition of each data stack. This paper explains how to make a stack diagram.

Let's talk about a stack diagram.

For example, the following is the case:

A company, selling three kinds of products: personal computers, smartphones, software.

In 2005, the profits of three products were 3000, 2000 and 11 million respectively.

In 2006, the profits of three products were 1300, 4000 and 17 million respectively.

Calculated, the total profit in 2005 was 61 million, 2006 was 70 million.

If you want to represent the profit of 2005 in a column, you should draw three rectangles and three rectangles stacked together. At this point, there is a question: what is the starting y-coordinate of each rectangle and how high it should be?

Input array, directly calculate the above problem, is the stack diagram layout.


1. Data

The data of a company selling personal computers, smartphones and software are as follows:

var DataSet = [{name: "PC",   sales: [{year:2005, profit:3000},{year:2006, profit:1300},{year:2007, profit:370  0},{year:2008, profit:4900},{year:2009, profit:700}]},{name: "SmartPhone",   sales: [{year:2005, profit:2000 },{year:2006, profit:4000},{year:2007, profit:1810},{year:2008, profit:6540},{year:2009, profit:2820}]},{na Me: "Software",   sales: [{year:2005, profit:1100},{year:2006, profit:1700},{year:2007, profit:1680},{year:20 , profit:4000},{year:2009, profit:4900}]}    ];

The dataset is an array, and each item of the array is an object that contains name and sales. Name is the product name, and sales is the selling situation. Sales is also an array, and each item is also an object, and the object contains a year representing the years, and profit represents the profit.

Now you want to plot this data as a stack diagram.


2. Layout (data conversion)

Create a stack diagram layout first.

var stack = D3.layout.stack (). VALUES (function (d) {return d.sales;}). X (function (d) {return d.year;}). Y (function (d) {return d.profit;});

The values accessor specifies the D.sales, which represents the array to be received next, the data to be computed in the variable sales for each item in the array. The x accessor specifies that the d.year,y accessor specifies the D.profit, which is said relative to the object specified by the values accessor, which is the variable year and profit for each item in the sales array.

With the dataset as the stack parameter, the result is stored in data:

var data = stack (dataset); Console.log (data);

Note that the original data will also change after the conversion, so the dataset and data values are the same. The output value of data 1 is shown. You can see that each item in sales has two more values: Y0 and Y. Y0 is the starting coordinate of the layer, and y is the height. The x-coordinate has the year.

Figure 1


3. Draw

The first is to create the x-axis and y-axis scales, which are used when adding graphical elements and axes. To draw an axis, immediately think of leaving a portion of the axis's scale blank. Define an outer border object first.

var padding = {left:50, right:100, top:30, bottom:30};

The right part of the space left more, is to add tags later. The x-axis scale is defined as follows:

var xrangewidth = Width-padding.left-padding.right;var XScale = d3.scale.ordinal (). Domain (Data[0].sales.map (function (d) {return d.year;}). Rangebands ([0, xrangewidth],0.3);

In this example, the x-axis represents the year, the 2005, 2006, and 2007, etc., are discrete, that is, the scale of the definition of the domain is discrete. From the content of the 5th chapter, the definition domain of ordinal scale d3.scale.ordinal is discrete. The above code sets the definition field to:

[2005, 2006, 2007, 2008, 2009]

The range is calculated based on rangebands () and is actually:

[31, 134, 238, 342, 446]//(omitted decimal point)

Thus, the x-coordinate of the rectangle stacked at 2005 is 31.

Then create a scale bar for the y-axis.

        Maximum profit (defines the maximum value of the field) var Maxprofit = D3.max (Data[data.length-1].sales, function (d) {return d.y0 + d.y;}); /maximum height (maximum value of the range) var yrangewidth = Height-padding.top-padding.bottom;var Yscale = d3.scale.linear (). Domain ([0, Maxprofit] )//define the field. Range ([0, Yrangewidth]);//Domain

In this code, for maximum profit, the maximum value of sales is obtained for the last item in the data array, data[2]. This is because Data[2] represents the highest layer, as shown in 2, each y0+y in the data[2].sales must be larger than data[1] and data[0]. So, just use D3.max () to find the maximum value in Data[2].sales. The range is the height of the SVG minus the upper and lower widths of the outer box. Then define the domain and value range for the d3.scale.linear () setting.

Figure 2

With the scale bar, you need to add a sufficient number of grouping elements <g> Each grouping represents a product, and each product is identified by a color.

        Color scale var = d3.scale.category10 ();//Add grouping element var groups = Svg.selectall ("G"). Data. Enter (). Append ("G"). Style ("Fill", function (d,i) {return color (i);});

Now 3 groups are added, representing the PC, SmartPhone, software, and the fill of each grouping element is set to color. Next, add a rectangle element for each grouping.

        Add the rectangle var rects = groups.selectall ("rect"). Data (function (d) {return d.sales;}). Enter (). Append ("Rect"). attr ("X", function (d) {return XScale (d.year);}). attr ("Y", function (d) {return Yrangewidth-yscale (d.y0 + d.y);}). attr ("width", function (d) {return Xscale.rangeband ();}). attr ("Height", function (d) {return Yscale (D.Y);}). attr ("Transform", "translate (" + Padding.left + ","    + padding.top + ")");

Each grouping element is also bound to the array sales to add a sufficient number of rectangles (each grouping of 5). Then use the scale bar to assign values to the X, Y, Width, and height properties of the rectangle. With the axis added, the result 3 shows.

Figure 3

However, what color represents what product can not be seen from the picture. The most common way to solve this problem is to add a few graphic markers next to the chart, plus text that tells the user what the color corresponds to. Continue to add graphical elements to the group, as shown in the code below.

        var labheight = 50;var Labradius = 10;var labelcircle = groups.append ("Circle"). attr ("CX", function (d) {return Width-padd ing.right*0.98; }). attr ("Cy", function (d,i) {return padding.top * 2 + labheight * i;}). attr ("R", Labradius), var labelText = groups.append ("text"). attr ("X", function (d) {return width-padding.right*0.8;}). attr ("Y", function (d,i) {return padding.top * 2 + labheight * i;}). attr ("dy", LABRADIUS/2). Text (function (d) {return d.name;});

Use circles and text as labels to add to the right side of the chart. As shown in final result 4.

Figure 4

Full code Please click the following URL, and then right click to view the source code:

Http://www.ourd3js.com/demo/G-3.0/stack.html

Thank you for reading.

Document Information
    • Copyright Notice: Attribution (by)-Non-commercial (NC)-No deduction (ND)
    • Published: March 29, 2015
    • More content: our D3. JS-Data Visualization special station and CSDN personal blog
    • Remark: This article is published in our D3. JS, reproduced please indicate the source, thank you

"D3.js Advanced Series-3.0" stack diagram

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.