Welcome to Tencent Cloud + community, get more Tencent mass technology practice dry goods oh ~

This article was published by Mr. Log Bridge in cloud + community column

introduce

D3.js is a JavaScript library. Its full name is Data-driven Documents, and it is called an interactive and dynamic network of Data visualization libraries. First released in February 2011, at the time of this writing, the latest stable release is version 4.4, with continuous updates. D3 utilizes scalable vector graphics or SVG format, allowing you to render zoomable or zoomable shapes, lines, and fills without compromising quality. This tutorial will guide you through creating bar charts using the JavaScript D3 library.

To prepare

To get the most out of this tutorial, you should be familiar with the JavaScript programming language as well as CSS and HTML.

Although you will be using CSS for D3 styling, it is worth noting that much of the standard CSS used in HTML will be used differently in SVG – that is, you will use stroke instead of border, and fill instead of color.

We’ll use a text editor and a Web browser. For testing purposes, it is recommended to use Tools to check and debug JavaScript, HTML, and CSS, such as Firefox Developer Tools or Chrome DevTools.

Step 1 – Create the file and refer to D3

Let’s start by creating a directory to hold all our files. You can call it as you like, and we call it the D3 project. After creation, go to the directory.

mkdir D3-project
cd D3-project
Copy the code

To use D3’s functionality, you must include the d3.js file in your web page. It is about 16,000 rows long and about 500KB in size.

Using curl to download the file to our directory.

To download the compressed version that is best for including your project, enter:

curl https://d3js.org/d3.v4.min.js --output d3.min.js
Copy the code

If you intend to read the D3 code, it is best to get the uncompressed version by typing the following:

curl https://d3js.org/d3.v4.js --output d3.js
Copy the code

We will use the d3.min.js file in this tutorial, please refer to d3.js in your HTML file.

Because D3 is modular, you can reduce the file size by pulling in only the modules you will use.

After downloading D3, let’s set up the CSS and HTML files. You can select the text editor you want to use on this file, such as Nano. We’ll start with the CSS file style.css so that we can immediately link to it from the HTML file.

nano style.css
Copy the code

We’ll start with a standard CSS declaration that sets the page to 100% height and infinity.

html, body {
  margin: 0;
  height: 100%;
}
Copy the code

You can now save and close the CSS file.

Next we’ll create our JavaScript file, which we’ll call barchart.js, and we’ll make bar charts for this example. Use the touch command to create the file without editing it.

touch barchart.js
Copy the code

Now, let’s concatenate all these elements into an HTML file, which we’ll call barchart.html:

nano barchart.html
Copy the code

We can set this up like most other HTML files, where we’ll reference the style.css file, barchart.js file and the script d3.min.js that we just created. Edit the barchart. HTML

<! DOCTYPE html> <html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Bar Chart</title>
    <link rel="stylesheet" type="text/css" href="style.css"> <! -- Alternatively use d3.js here --> <scripttype="text/javascript" src="d3.min.js"></script>

  </head>

  <body>
    <script type="text/javascript" src="barchart.js"></script>
  </body>
</html>
Copy the code

Save and close.

Step 2 – Set up SVG in JavaScript

We can now open the file barchart.js using the text editor of our choice:

nano barchart.js
Copy the code

Let’s start by adding an array of numbers that we’ll use as the base for our barchart. Edit barchart.js:

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];
Copy the code

Next, we need to create an SVG element. This is where we store all the graphics. In D3, we use d3.select to make the browser search for elements.

We can use d3.select(“body”).append(” SVG “); Perform this operation. Edit the barchart. Js

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg");
Copy the code

If we now load barchart.html into our Web browser, we should be able to use our developer tools to examine the DOM or document object model and hover over the SVG box.

Back in our JavaScript file, we can link properties to SVG to make it the full height and width of the web page. We use.attr() for attributes. To make it more readable. Be sure to move the semicolon down to the end of the variable declaration. Edit the barchart. Js

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");
Copy the code

If you reload the page in your browser, you should see a rectangle that takes up the entire screen when you hover over the DOM.

Step 3 – Add rectangle

With our SVG ready, we can start adding the rectangles of our dataset to the JavaScript file, editing barchart.js.

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect");
Copy the code

As with d3.select above, let the browser search for elements. This time, it’s a rectangular array. Since it is an array, we use d3.selectAll and d3.selectAll(“rect”) because it is a rectangular array. If the browser finds rectangles, it will return them in the selection, and if it is empty, it will return null. With D3, you must first select the elements you want to work with.

Data (dataArray) Array of data stored in dataArray.

To actually add a rectangle for each item in the selection (corresponding to the data array), we will also add.enter().append(“rect”); To append the rectangle. In this example, there will be nine rectangles corresponding to nine numbers in the array.

If you reload the page now, you won’t see any rectangles, but if you examine the DOM, you’ll see nine rectangles defined there.

We haven’t set the properties for the rectangles to make them visible, so add them now.

Sets the properties of the shape

We can add attributes to shapes in the same way we defined attributes for SVG, using.attr(). Each shape in D3 will have different properties, depending on how they are defined and drawn.

Our rectangle will contain four properties:

  • ("height", "height_in_pixels")The height of the corresponding rectangle
  • ("width", "width_in_pixels")Width of the corresponding rectangle
  • ("x", "distance_in_pixels")Represents the distance from the left side of the browser window
  • ("y", "distance_in_pixels")Represents the distance from the top of the browser window

So if we wanted a rectangle 250 pixels long, 40 pixels wide, 25 pixels from the left side of the browser, and 50 pixels from the top, we would write the following code:


var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("height"."250")
          .attr("width"."40")
          .attr("x"."25")
          .attr("y"."50");
Copy the code

If we refresh the browser, we see all the rectangles overlap:

By default, shapes in D3 are filled with black, but we can change this later as we need to address the positioning and size of the rectangle first.

Make the rectangle reflect the data

Currently, all rectangles in our array have the same position along the X-axis and do not represent height data. To change the position and size of the rectangle, we need to introduce functions for some of our properties. Adding a function makes the value dynamic rather than manual. Let’s start by modifying the X property. Currently, this line looks like this:

        .attr("x"."25")
Copy the code

We will replace the 25 pixel number with a function. We will pass two variables function() defined by D3, representing data points and indexes. The index tells us where the data points are in the array. D is the convention for data points and I indexes, such as function(d, I), but you can use any variable you want.

JavaScript iterates over D and I. Let’s add spacing for each index of its iteration so that each rectangle is spaced. To do this, we can multiply the index by I by a certain number of pixels. We will use 60 for now, but you can decide which pitch is right for you. Our new X-axis property row now looks like this:

        .attr("x".function(d, i) {returni * 60; })Copy the code

However, if we run the code now, we’ll see that the rectangle is flush on the left side of the browser, so let’s add some extra spacing there, say 25 pixels from the edge. Our complete code should now look like this:

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("height"."250")
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y"."50");
Copy the code

If we refresh the browser at this point, we should see something like this:

Now we have rectangles spaced along the X axis that represent each item in our array. Next, let the height of the rectangle reflect the data in the array.

We will now use the height property and add a function similar to the one we added to the x property. Let’s start d and I into function by passing variables and return d. D stands for data point.

.attr(“height”, function(d, i) {return (d)})

If you run the code now, you’ll notice two things. First, the rectangles are fairly small, and second, they are attached to the top of the chart rather than the bottom.

To solve for the small size of the rectangle, let’s multiply what d returns:

          .attr("height".function(d, i) {return (d * 10)})
Copy the code

The rectangles are now larger in size, but they are still displayed from top to bottom. Browsers usually read web pages from the top left to the bottom right, while we read bar charts from the bottom to the top. To reposition the rectangle, we will change the y property to subtract the space at the top.

Again, we’ll use function(d, I), and we’ll return a Y value higher than the highest value of our bar graph, say 400. We will subtract the returned height (d * 10) from 400 so that our row now looks like this:

          .attr("y".function(d, i) {return 400 - (d * 10)});
Copy the code

Let’s take a look at our complete JavaScript code:

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("height".function(d, i) {return (d * 10)})
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)});
Copy the code

At this point, when we reload the page, we see a bar chart that we can read from bottom to top:

Now we can style the diagram.

Step 4 – Set styles using D3

We’ll use our CSS file to design our D3 shape, but first, to make the job easier, we’ll provide our rectangle with a class name in our JavaScript file that we can reference in our CSS file.

Adding a class is just like adding any other property using dot notation. We call it the class bar because it’s a bar chart, but we can call it as long as all references refer to the same name. Our syntax looks like this:

          .attr("class"."bar")
Copy the code

We can add this property anywhere. Keeping it as the first property makes it easier to reference in our CSS files.

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("class"."bar")
          .attr("height".function(d, i) {return (d * 10)})
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)});
Copy the code

Now, let’s switch to our style.css file, which currently looks like this:

html, body {
  margin: 0;
  height: 100%
}
Copy the code

We can start modifying the rectangle by changing the fill color, referencing the bar category we just created:

style.css
html, body {
  margin: 0;
  height: 100%
}

.bar {
  fill: blue
}
Copy the code

Here, we set the rectangles to blue, and we can also assign them a hexadecimal color code, as follows:

.bar {
  fill: #0080FF
}
Copy the code

At this point, our rectangle looks like this:

We can provide other values for the rectangle, such as stroke to outline the rectangle in a specific color, and stroke-width:

html, body {
  margin: 0;
  height: 100%
}

.bar {
  fill: #0080FF;
  stroke: black;
  stroke-width: 5
}
Copy the code

This will give our rectangle a black outline with a width of 5 pixels.

Additionally, we can add some interactivity to our chart by adding bar color styles over mouse hover:

.bar:hover {
  fill: red
}
Copy the code

Now, when we hover over one of the rectangles, that particular rectangle will turn red:

Alternatively, you can set shape styles in JavaScript files by adding additional properties. In rectangle blocks, we’ll write these just like any other.attr() property. Therefore, adding black strokes around the rectangle will be written.attr(“stroke”, “black”). We also add stroke-width pixels and make sure to move the semicolon down.

. svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("class"."bar")
          .attr("height".function(d, i) {return (d * 10)})
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)})
          .attr("stroke"."black")
          .attr("stroke-width"."5");
Copy the code

You can choose how to decide on styles and file styles. In this example, we will operate in the style.css file and limit it to fill colors and hover fill:

html, body {
  margin: 0;
  height: 100%
}

.bar {
  fill: #0080FF
}

.bar:hover {
  fill: # 003366
}
Copy the code

When working with color on the Web, it’s important to keep your audience in mind and strive to include colors that are as universally accessible as possible.

Step 5 – Add labels

Our final step is to add some quantifiable markers to our chart in the form of labels. These labels will correspond to the numbers in our array.

Adding text is similar to adding the rectangle shape we made above. We need to select the text and attach it to SVG. We also associate it with the dataArray we created. We’ll use “text” instead of “rect”, but the general format is similar to what we did when we added the rectangle above. We add these lines to the bottom of the barchart.js file.

var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("class"."bar")
          .attr("height".function(d, i) {return (d * 10)})
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)});

svg.selectAll("text")
    .data(dataArray)
    .enter().append("text")
    .text(function(d) {returnd; });Copy the code

When we refresh the browser, we won’t see any text on the page, but we’ll see it again in the DOM:

If you hover over a line of text in the DOM, you’ll see that the text is all at the top of the page, where X and Y are equal to 0. We will use the same function formula as ours to modify the position by adding attributes for the rectangle.

. svg.selectAll("text")
    .data(dataArray)
    .enter().append("text")
    .text(function(d) {return d})
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)});
Copy the code

When you load the page now, you see the numbers floating above the bar chart.

It’s worth noting that because this is SVG and not an image, you can select text just like any other text you see on the page.

From here, you can reposition the numbers by modifying the function formula. You might want to float them over a bar chart, for example:

. svg.selectAll("text")
    .data(dataArray)
    .enter().append("text")
    .text(function(d) {return d})
          .attr("x".function(d, i) {return (i * 60) + 36})
          .attr("y".function(d, i) {return 390 - (d * 10)});
Copy the code

Alternatively, you can float the numbers on the rectangle by modifying their position according to the Y-axis. We also want to make it more readable, so let’s add a class that we can access from the style.css file.

. .text { fill: white; font-family: sans-serif }Copy the code

You can modify as much of the text as possible by positioning and styling. For example, you might also want to change the font-size property in the style.css file.

Completed code and code improvements

At this point, you should have a fully functional bar graph rendered in the JavaScript D3 library. Let’s look at all our code files.

barchart.html
Copy the code
<! DOCTYPE html> <html lang="en">
  <head>
    <meta charset="utf-8"> <title>Bar Chart</title> <! -- Reference style.css --> <link rel ="stylesheet" type="text/css" href="style.css"> <! -- Reference minified version of D3 --> <scripttype="text/javascript" src="d3.min.js"></script>
  </head>

  <body>
    <script type="text/javascript" src="barchart.js"></script>
  </body>
</html>
Copy the code
style.css
Copy the code
html, body {
  margin: 0;
  height: 100%
}

/*Rectangle bar class styling*/

.bar {
  fill: #0080FF
}

.bar:hover {
  fill: # 003366
}

/*Text class styling*/

.text {
  fill: white;
  font-family: sans-serif
}
Copy the code
barchart.js
Copy the code
// Create data array of values to visualize
var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];

// Create variable for the SVG
var svg = d3.select("body").append("svg")
          .attr("height"."100%")
          .attr("width"."100%");

// Select, append to SVG, and add attributes to rectangles for bar chart
svg.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
          .attr("class"."bar")
          .attr("height".function(d, i) {return (d * 10)})
          .attr("width"."40")
          .attr("x".function(d, i) {return (i * 60) + 25})
          .attr("y".function(d, i) {return 400 - (d * 10)});

// Select, append to SVG, and add attributes to text
svg.selectAll("text")
    .data(dataArray)
    .enter().append("text")
    .text(function(d) {return d})
           .attr("class"."text")
           .attr("x".function(d, i) {return (i * 60) + 36})
           .attr("y".function(d, i) {return 415 - (d * 10)});
Copy the code

This code is perfectly normal, but you can do a lot to improve it. For example, you can group SVG elements together using SVG group elements, allowing you to modify text and rectangles in fewer lines of code.

You can also access data in different ways. We use arrays to hold our data, but you might want to visualize the data you already have access to, and it might be much more than the data in the array. D3 will allow you to use several different data file types:

  • HTML
  • JSON
  • Plain text
  • CSV (comma-separated values)
  • TSV (TAB separated values)
  • XML

For example, you can have a JSON file in your website’s directory and link it to a JavaScript file

d3.json("myData.json".function(json) {
// code for D3 charts in here
});
Copy the code

You can also combine the D3 library with other interactive features that you might already know from Vanilla JavaScript.

conclusion

This tutorial works by creating bar charts in the JavaScriptD3 library. You can learn more about d3.js by visiting the D3 API on GitHub. For more front-end tutorials, please go to Tencent Cloud + community to learn more knowledge.


Reference: Getting Started with Data Visualization Using JavaScript and the D3 Library

Question and answer

Tencent cloud server?

reading

Teach you from 0 to 1 build small program audio and video

Teach you how to quickly build a press conference live program

Shape shifter – The story behind short video color effects

This article has been published by Tencent Cloud + community authorized by the author.Cloud.tencent.com/developer/a…

Welcome to Tencent Cloud + community or follow the wechat public account (QcloudCommunity), the first time to get more mass technology practice dry goods oh ~

Massive technical practice experience, all in the cloud plus community! Cloud.tencent.com/developer?f…