Category Archives: web design

Force-Directed Graph with D3.js

Network visualizations involve displaying interconnected nodes commonly associated with social networks. D3.js has powerful capabilities to create these visualizations. In this post, we will learn how to make a simple force-directed graph.

A force directed graph uses an algorithm that spaces the nodes in the graph away from each other based on a value you set. There are several different ways to determine how the force influences the distance of the nodes from each other that will be explored somewhat in this post.

1.jpg

The Data

To make the visualization it is necessary to have data. We will use a simple json file that has nodes and edges. Below is the code

{

"nodes": [

{ "name": "Tom" },

{ "name": "Sue" },

{ "name": "Jina" },

{ "name": "Soli" },

{ "name": "Lala" }

],

"edges": [

{ "source": 0, "target": 1 },

{ "source": 0, "target": 4 },

{ "source": 0, "target": 3 },

{ "source": 0, "target": 4 },

{ "source": 0, "target": 2 },

{ "source": 1, "target": 2 }

]

}

The nodes in this situation will represent the circles that we will make. In this case, the nodes have names. However, we will not print the names in the visualization for the sake of simplicity. The edges represent the lines that will connect the circles/nodes. The source number is the origin of the line and the target number is where the line ends at. For example, “source: 0” represents Tom and “Target”: 1 means draw a line from Tom to Sue.

Setup

To begin the visualization we have to create the svg element inside our html doc. Lines 6-17 do this as shown below.

1.png

Next, we need to create the layout of the graph. The .node() and the .link() functions affect the location of the nodes and links. The .size() affects the gravitational center and initial position of the visualization. There is also some code that is commented out in below that will be discussed later. Below are lines 18-25 of our code.

1

Now we can write the code that will render or draw our object. We need to append the edges and nodes, indicate color for both, as well as the radius of the circles of the nodes. All of this is captured in lines 26-44

1

The final step is to handle the ticks. To put it simply, the ticks handles recalculating the position of the nodes. Below is the code for this.

1

We can finally see are visual as shown below

You can clearly see that the nodes are on top of each other. This is because we need to adjust the use of the force in the force-directed graph. There are many ways to adjust this, but we will look at two functions. These are .linkDistance() and .charge().

The .linkDistance() function indicates how far nodes are from each other at the end of the simulation. To add this to our code you need to remove the comments on line22 as shown below.

1

Below is an update of what our visualization  looks like.

Things are better but the nodes are still on top of each other. The real differences is that the edges are longer. To fix this, we need to use the .charge() function. The .charge() function indicates how much nodes are attracted to each other or repel each other. To use this function you need to remove the comments on line 23 as shown below.

1

The negative charge will cause the nodes to push away from each other. Below is what this looks like.

You can see that as the nodes were moved around the stayed far from each other. This is because of the negative charge. Off course, there are other ways to modify this visualization but this is enough for now.

Conclusion

Force-directed graphs are a  powerful tool for conveying what could be a large amount of information. This post provided some simple ways that this visualization can be developed and utilized for practical purposes.

Pie Charts with D3.js

Pie charts are one of many visualizations that you can create using D3.js. We are going to learn how to do the following in this post.

  • Make a circle
  • Make a donut
  • Make a pie wedge
  • Make a segment
  • Make a pie chart

Most of these examples require just a minor adjustment in a standard piece of code. This  will make more sense in a minute.

Make a Circle

Making a circle involves using the .arc() method. In this method there are four parameters that you manipulate to get different shapes. They are explained below

  • .innerRadius() This parameter makes a whole in your circle to give the appearance of a donut
  • .outerRadius() Determines the size of your circle
  • .startAngle() is used in combination with .endAngle() to make a pie wedge

Therefore, to make several different shapes we manipulate these different parameters. In the code below, we create the svg element first (lines 7-10)  then our circle (lines 11-15). Lastly, we append the path to the svg element (lines 16-21). Below is the code and picture.

12

The rest of the examples primarily deal with manipulating the existing code.

Donut

To make the donut, you need to change the value inside the .innerRadius() parameter. The larger the value the bigger the hole in the middle of the circle will become. In order to generate the donut below you need to change the value found in line 12 of  the code to 100.

1.png

Pie Wedge

To make a wedge you need to replace lines 14-15 of the code with the following

.startAngle(0*Math.PI * 2/360)

.endAngle(90*Math.PI * 2/360);

This is telling d3.js to start the angle at 0 degrees and stop at 90 degrees. This is another way of saying making a wedge of 1/4 of the circle. Doing this will create the following.

1

Segment

In order to make the segment you keep the code the same as above for the pie wedge but at a change to the .innerRadius() parameter. AS shown below,

.innerRadius(100)

.outerRadius(170)

.startAngle(0*Math.PI * 2/360)

.endAngle(90*Math.PI * 2/360);

1

Pie Chart

A pie chart is just a more complex version of what we have already done. You still need to set up your svg element. This is don in lines 7-14. Notice that we also had to add a g element and a transform attribute.

Line 16 contains the data for making the pie chat. This is hard coded but we can also use other forms of data. Line 17 uses the .pie() method with the data to set the stage for our pie chart.

Lines 19-27 are for generating the arc. This code is mostly the same except for the functions that are used for the .startAngle() and .end Angle() methods. Line 29 sets the color and Lines 30-42 draw the paths for creating the image. The code with the // will be explained in a moment. Below is the code and the pie chart.

12

Pie Chart Variation

Below is the same pie chart but with some different features.

  • It now has a donut (line 20 change .innerRadius(0) to .innerRadius(50))
  • There are now separations between the different segments to give the appearance that it is pulling apart. Remove the // in lines 36-37 to activate this.

Below is the pie chart

1.png

You can perhaps now see that the possibilities are endless with this.

Conclusion

Pie charts and their related visualizations are another option for communicating insights of data

Dendrogram with D3.js

Dendrogram is a type of hierarchical visualization commonly used in data science with hierarchical clustering. In d3.js, the dendrogram looks slightly different in that the root is in the center and the nodes branch out from there. This idea continues for every parent child relationship in the data.

In this post, we will make a simple dendrogram with d3.js using   a simple json file shown below.

{

  "name": "President",

          "children": [

        { "name": "VP of Academics",

        "children":[

          {"name":"Dean of Psych"},

          {"name":"Dean of Ed"}

        ] },

       { "name": "VP of Finance" },

        { "name": "VP of Students" }

      ]

    }

You will need to save the code above as a json file if you want to make this example. In the code, this json example is called “university.json”

Making the Dendrogram

We will begin by setting up the basic svg limit as found in lines 1-19 below.
1.png

In lines 20-26, the radius of the nodes is set and added to the svg element. The clusters are set with the creation of the cluster variable. Below is the code.

1.png

In lines 27-37, we set the position of the nodes and links as well as diagonals for the path.

1

Lines 49-80, have three main blocks of code.

The first block creates a variable called nodesGroups. This code provides a place to hold the nodes and the text that we are going to create.

The second block of code is adding circles to the nodeGroups with  additional settings for the color and radius size. Lastly, the third block of code adds texts to the nodesGroups.

1.png

When all the steps have been taken, you will see the following when you run the code.

1.png

You can see how things worked. The center is the president with the vp of academics of to the right. The president has three people under him (all VPs) while the VP of academics has two people under him (deans). The colors for the path and the circle are all set in the last block of code that was discussed.

Conclusion

Dendrograms allow you to communicate insights about data in a distinctly creative way. This example was simplistic but serves the purpose of exposing you to another way  of using d3.js

Tree Diagram with D3.js

Tree diagrams are used for showing hierarchical relationships in data. This post will explain how to make a tree diagram using d3.js.

The Data

We are going to use a simple json file. Below is the code inside the json file.

{

"name": "President",

"children": [

{ "name": "VP of Academics",

"children":[

{"name":"Dean of Psych"},

{"name":"Dean of Ed"}

] },

{ "name": "VP of Finance" },

{ "name": "VP of Students" }

]

}

The code above is json file that models relationships among different positions you would find at a university. The root node is “president”. Under president, there are three children which are “VP of academics”, “VP of Finance”, and “VP of students”.

VP of academics also has two children which are “Dean of Psych” and “Dean of Ed.” You need to save this code on your computer somewhere as a json file for use in the d3.js code.

Below is a picture of what the final visual looks like.

1

The code is too long to post in its entirety here. Rather, you can download the code at the link here.

The code is explained below.

Code Description

Lines 1-26 setup the general documents, loads the data, adds an svg element to the body, and a g element to the svg element. Below is the code.

1.png

Lines 27-34 creates the actual tree and creates variables for the nodes and links that will be used later.

1.png

Lines 36-50 creates the diagonals and the nodes for the diagram. The diagonal is created using the .projection() method. Attributes are set for the diagonal as well under the .selectAll() method and includes the stroke color, width of the stroke, and the fill. The code is below.

1.png

Lines 52-66 create the circles for each node. This involves appending information in the element as well as setting colors for the circles.

1.png

Finally, lines 68-85 involve the text from the json file. The first method calls the text, the second method deals with position, and the last method also addresses position somewhat.

1

A lot of work but can be valuable in certain situations.

Conclusion

Making tree diagrams is another visualization available using d3.js. If the nature of the data is hierarchical this may be a useful approach to consider when make visualizations.

Path Generators in D3.js

D3.js has the ability to draw rather complex shapes using techniques called path generators. This will allow you to many things that would otherwise be difficult when working with visualizations.

In this post, we will look at three different examples of path generation involving d3.js. The three examples are as follows

  • Making a triangle
  • Duplicating the triangle
  • Make an area chart

Making a Triangle

To make a triangle we start by appending a svg to the body element of our document (lines 7-12). Then when create an array that has three coordinates. We need three coordinates because that is how many coordinates a triangle needs (lines 13-17). After this, we create a variable called generate and use the .svg.line() method to draw the actual lines that we want (lines 18-20).

After this, we append the data and other characteristics to the svg variable. This allows us to set the fill color and the line color (lines 21-28). Below is the code followed by the output.

12

A simple triangle was created with only a few lines of code.

Create a Triangle and Duplicate

This example is an extension of the previous one. Here, we create the same triangle, but then we duplicate it using the translate method. This is a powerful technique if you need to make the same shape more than once.

The new code is found in lines 29-36

12

You can see that the new triangle was moved to a different position based on the arguments we gave it.

Area Chart

Area charts are often used to make line plots but with the area under the line being filled with a certain color. To achieve this we do the following.

  • Add our svg element to the body element (lines 7-10)
  • Create some random data using the .range() method and several functions (lines 12-18)
    • we generate 1000 random numbers (line 12) between 0 and 100 (line 14)
    •   We set the Y values as random values of X in increments of 10 (line16-17)
  • We create a variable called generate to create the path using the .area() method (line 20-23)
    • y0 has to do with the height or depth of the area the other two attributes are the X and Y values
  • We then append all this to the svg variable we created (lines 25-31)

Below is the code followed by the visual.

12

Much more can be done with this but I think this makes the point for now.

Conclusion

This post was just  an introduction to making paths with D3.js.

Drag, Pan, & Zoom Elements with D3.js

Mouse events can be combined in order to create some  rather complex interactions using d3.js. Some examples of these complex actions includes dragging,  panning, and zooming. These events are handle with tools called behaviors. The behaviors deal with dragging, panning, and zooming.

In this post, we will look at these three behaviors in two examples.

  • Dragging
  • Panning and zooming

Dragging

Dragging allows the user to move an element around on the screen. What we are going to do is make three circles that are different colors that we can move around as we desire within the element. We start by setting the width, height of the svg element as well as the radius of the circles we will make (line 7). Next, we create our svg by appending it to the body element. We also set a black line around the element so that the user knows where the borders are (lines 8-14).

The next part involves setting the colors for the circles and then creating the circles and setting all of their attributes (lines 21 – 30). Setting the drag behavior comes later, and we use the .drag() and the .on() methods t create this behavior and the .call() method connects the information in this section to our circles variable.

The last part is the use of the onDrag function. This function retrieves the position of the moving element and transform the element within the svg element (lines 36-46). This involves using an if statement as well as setting attributes. If this sounds confusing, below is the code followed by a visual of what the code does.

1

If you look carefully you will notice I can never move the circles beyond the border. This is because the border represents the edge of the element. This is important because you can limit how far an element can travel by determining the size of the elements space.

Panning and Zooming

Panning allows you to move all visuals around at once inside an element. Zooming allows you to expand or contract what you see. Most of this code is a extension  of the what we did in the previous example. The new additions are explained below.

  1. A variable called zoomAction sets the zoom behavior by determining the scale of the zoom and setting the .on() method (Lines 9-11)
  2. We add the .call() method to the svg variable as well as the .append(‘g’) so that this behavior can be used (Lines 20-21).
  3. The dragAction variable is created to allow us to pan or move the entire element around. This same variable is placed inside a .call() method for the circles variable that was created earlier (Lines 40-46).
  4. Lines 48-60 update the position of the element by making two functions. The onDrag function deals with panning and the onZzoom function deal with zooming.

Below is the code and a visual of what it does.

You can clearly see that we can move the circles individually or as a group. In addition, you also were able to see how we could zoom in and out. Unlike the first example this example allows you to leave the border. This is probably due to the zoom capability.

Conclusion

The behaviors shared here provide additional tools that you can use as you design visuals using D3.js. There are other more practical ways to use these tools as we shall see.

Intro to Interactivity with D3.js

The D3.js provides many ways in which the user can interact with visual data. Interaction with a visual can help the user to better understand the nature and characteristics of the data, which can lead to insights. In this post, we will look at three basic examples of interactivity involving mouse events.

Mouse events are actions taken by the browser in response to some action by the mouse. The handler for mouse events is primarily the .on() method. The three examples of mouse events in this post are listed below.

  • Tracking the mouse’s position
  • Highlighting an element based on mouse position
  • Communicating to the user when they have clicked on an element

Tracking the Mouses’s Position

The code for tracking the mouse’s position is rather simple. What is new is Is that we need to create a variable that appends a text element to the svg element. When we do this we need to indicate the position and size of the text as well.

Next, we need to use the .on() method on the svg variable we created. Inside this method is the type of behavior to monitor which in this case is the movement of the mouse. We then create a simple way for the browser to display the x, y coordinates.  Below is the code followed by the actual visual.

1.png

You can see that as the mouse moves the x,y coordinates move as well. The browser is watching the movement of the mouse and communicating this through the changes in the coordinates in the clip above.

Highlighting an Element Based on Mouse Position

This example allows an element to change color when the mouse comes in contact with it. To do this we need to create some data that will contain the radius of four circles with their x,y position (line 13).

Next we use the .selectAll() method to select all circles, load the data, enter the data, append the circles, set the color of the circles to green, and create a function that sets the position of the circles (lines 15-26).

Lastly, we will use the .on() function twice. Once will be for when the mouse touches the circle and the second time for when the mouse leaves the circle. When the mouse touches a circle the circle will turn black. When the mouse leaves a circle the circle will return to the original color of green (lines 27-32). Below is the code followed by the visual.

1

Indicating when a User Clicks on an Element

This example is an extension of the previous one. All the code is the same except you add the following at the bottom of the code right before the close of the script element.

.on('click', function (d, i) {

alert(d + ' ' + i);

});

This .on() method has an alert inside the function. When this is used it will tell the user when they have clicked on an element and will also tell the user the radius of the circle as well what position in the array the data comes from. Below is the visual of this code.

Conclusion

You can perhaps see the fun that is possible with interaction when using D3.js. There is much more that can be done in ways that are much more practical than what was shown here.

Tweening with D3.js

Tweening is a tool that allows you to tell D3.js how to calculate attributes during transitions without keyframes tracking. The problem with keyframes tracking is that it can develop performance issues if there is a lot of animation.

We are going to look at three examples of the use of tweening in this post. The examples are as follows.

  • Counting numbers animation
  • Changing font size animation
  • Spinning shape animation

Counting Numbers Animation

This simple animation involves using the .tween() method to count from 0 to 25. The other information in the code determines the position of the element, the font-size, and the length of the animation.

In order to use the .tween()  method you must make a function. You first give the function a name followed by providing the arguments to be used. Inside the function  we indicate what it should do using the .interpolateRound() method which indicates to d3.js to count from 0 to 25. Below is the code followed by the animation.

1

You can see that the speed of the numbers is not constant. This is because we did not control for this.

Changing Font-Size Animation

The next example is more of the same. This time we simply make the size of a text change. TO do this you use the .text() method in your svg element. In addition, you now use the .styleTween() method. Inside this method we use the .interpolate method and set arguments for the font and font-size at the beginning and the end of the animation. Below is the code and the animation1

Spinning Shape Animation

The last example is somewhat more complicated. It involves create a shape that spins in place. To achieve this we do the following.

  1. Set the width and height of the element
  2. Set the svg element to the width and height
  3. Append a group element to  the svg element.
  4. Transform and translate the g element in order to move it
  5. Append a path to the g element
  6. Set the shape to a diamond using the .symbol(), .type(), and .size() methods.
  7. Set the color of the shape using .style()
  8. Set the .each() method to follow the cycle function
  9. Create the cycle function
  10. Set the .transition(), and .duration() methods
  11. Use the .attrTween() and use the .interpolateString() method to set the rotation of the spinning.
  12. Finish with the .each() method

Below is the code followed by the animation.

1

This animation never stops because we are using a cycle.

Conclusion

Animations can be a lot of fun when using d3.js. The examples here may not be the most practical, but they provide you with an opportunity to look at the code and decide how you will want to use d3.js in the future.

Intro to Animation with D3.js

This post will provide an introduction to animation using D3.js. Animation simply changes the properties of the visual object over time. This can be useful for help the viewer of the web page to understand key features of the data.

For now we will do the following in terms of animation.

  • Create a simple animation
  • Animate multiple properties
  • Create chained transitions
  • Handling Transitions

Create a Simple Animation

What is new for us in terms of d3.js code for animation is the use of the .transition() and .duration() methods. The transition method provides instructions on how to changing a visual attribute over time. Duration is simply how long the transition takes.

In the code below, we are going to create a simply black rectangle that will turn white and disappear on the screen. This is done by appending an svg that contains a black rectangle into the body element and then have that rectangle turn white and disappear.

1

1.gif

This interesting but far from amazing. We simply change the color  or animated one property. Next, we learn how to animate more than one property at a time.

Animating Multiple Properties at Once

You are not limited to only animating one property. In the code below we will change the color will have the rectangle move as well. This id one through the x,y coordinates to the second .attr({}) method. The code and the animation are below.

12

You can see how the rectangle moves from the top left to the bottom right while also changing colors from black to white thus disappearing. Next, we will look at chained transitions

Chained Transitions

Chained transitions involves have some sort of animation take place. Followed by a delay and then another animation taking place. In order to do this you need to use the .delay() method. This method tells the  browser to wait a specify number of seconds before doing something else.

In our example, we are going to have our rectangle travel diagonally down while also disappearing only tot suddenly travel up while changing back to the color of black. Below is the code followed by the animation.

13

By now you are starting to see that the only limit to animation in d3.js is your imagination.

Handling Transitions

The beginning and end of a transition can be handle by a .each() method. This is useful when you want to control the style of the element at the beginning and or end of a transition.

In the code below, you will see the rectangle go from red, to green, to orange, to black, and then to gray. At the same time the rectangle will move and change sizes. Notice careful the change from red to green and form black to gray are controlled by .each() methods.

11

Conclusion

Animation is not to only be used for entertainment. When developing visualizations, an animation should provide additional understanding of the content that you are trying to present. This is important to remember so that d3.js does not suffer the same fate as PowerPoint in that people focus more on the visual effects rather than the content.

Adding labels to Graphs D3.js

In this post, we will look at how to add the following to a bar graph using d3.js.

  • Labels
  • Margins
  • Axes

Before we begin, you need the initial code that has a bar graph already created. This is shown below follow by what it should look like before we make any changes.

1

1

The first change is in line 16-19. Here, we change the name of the variable and modify the type of element it creates.

1.png

Our next change begins at line 27 and continues until line 38. Here we make two changes. First, we make a variable called barGroup, which selects all the group elements of the variable g. We also use the data, enter, append and attr methods. Starting in line 33 and continuing until line 38 we use the append method on our new variable barGroup to add rect elements as well as the color and size of each bar. Below is the code.

1.png

The last step for adding text appears in lines 42-50. First, we make a variable called textTranslator to move our text. Then we append the text to the bargroup variable. The color, font type, and font size are all set in the code below followed by a visual of what our graph looks like now.

12

Margin

Margins serve to provide spacing in a graph. This is especially useful if you want to add axes. The changes in the code take place in lines 16-39 and include an extensive reworking of the code. In lines 16-20 we create several variables that are used for calculating the margins and the size and shape of the svg element. In lines 22-30 we set the attributes for the svg variable. In line 32-34 we add a group element to hold the main parts of the graph. Lastly, in lines 36-40 we add a gray background for effect. Below is the code followed by our new graph. 1.png

1

Axes

In order for this to work, we have to change the value for the variable maxValue to 150. This would give a little more space at the top of the graph. The code for the axis goes form line 74 to line 98.

  • Line 74-77 we create variables to set up the axis so that it is on the left
  • Lines 78-85 we create two more variables that set the scale and the orientation of the axis
  • Lines 87-99 sets the visual characteristics of the axis.

Below is the code followed by the updated graph

12

You can see the scale off to the left as planned..

Conclusion

Make bar graphs is a basic task for d3.js. Although the code can seem cumbersome to people who do not use JavaScript. The ability to design visuals like this often outweighs the challenges.

Making Bar Graphs with D3.js

This post will provide an example of how to make a basic bar graph using d3.js. Visualizing data is important and developing bar graphs in one way to communicate information efficiently.

This post has the following steps

  1. Initial Template
  2. Enter the data
  3. Setup for the bar graphs
  4. Svg element
  5. Positioning
  6. Make the bar graph

Initial Template

Below is what the initial code should look like.

1

Entering the Data

For the data we will hard code it into the script using an array. This is not the most optimal way of doing this but it is the simplest for a first time experience.  This code is placed inside the second script element. Below is a picture.

1

The new code is in lines 10-11 save as the variable data.

Setup for the Bars in the Graph

We are now going to create three variables. Each is explained below

  • The barWidth variable will indicate ho wide the bars should be for the graph
  • barPadding variable will put space between the bars in the graph. If this is set to 0 it would make a histogram
  • The variable maxValue scales the height of the bars relative to the largest observation in the array. This variable uses the method .max() to find the largest value.

Below is the code for these three variables

1

The new information was added in lines 13-14

SVG Element

We can now begin to work with the svg element. We are going to create another variable called mainGroup. This will assign the svg element inside the body element using the .select() method. We will append the svg using .append and will set the width and height using .attr. Lastly, we will append a group element inside the svg so that all of our bars are inside the group that is inside the svg element.

The code is getting longer, so we will only show the new additions in the pictures with a reference to older code. Below is the new code in lines 16-19 directly  under the maxValue variable.

1

Positioning

New=x we need to make three functions.

  • The first function will calculate the x location of the bar graph
  • The second function  will calculate the y location of the bar graph
  • The last function will combine the work of the first two functions to place the bar in the proper x,y coordinate in the svg element.

Below is the code for the three functions. These are added in lines 21-251

The xloc function starts in the bottom left of the mainGroup element and adds the barWidth plus the barPadding to make the next bar. The yloc function starts in the top left and subtracts the maxValue from the given data point to calculate the y position. Lastly, the translator combines the output of both the xloc and the yloc functions to position bar using the translate method.

Making the Graph

We can now make our graph. We will use our mainGroup variable with the .selectAll method with the rect argument inside. Next, we use .data(data) to add the data, .enter() to update the element, .append(“rect”) to add the rectangles. Lastly, we use .attr() to set the color, transformation, and height of the bars. Below is the code in lines 27-36 followed by actual bar graph. 1.png

1

The graph is complete but you can see that there is a lot of work that needs to be done in order to improve it. However, that will be done in a future post.

SVG and D3.js

Scalable Vector Graphics or SVG for short is a XML markup language that is the standard for creating vector-based graphics in web browsers. The true power of d3.js is unlocked through its use of svg elements. Employing vectors allows for the image that are created to be various sizes based on scale.

One unique characteristic of svg is that the coordinate system starts in the upper left with the x axis increases as normal from left to right. However, the y axis starts from the top and increases going down rather than the opposite of increasing from the bottom up. Below is a visual of this.

1

You can see that (0,0) is in the top left corner. As you go to the right the x-axis increases and as you go down the y axis increases.  By changing the x, y axis values you are able to position your image where you want it. If you’re curious the visual above was made using d3.js.

For the rest of post, we will look at different svg elements that can be used in making visuals. We will look at the following

  • Circles
  • Rectangles/squares
  • Lines & Text
  • Paths

Circles

Below is the code for making circle followed by the output

1.png

1.png

To make a shape such as the circles above, you first must specify the size of the svg element as shown in line 6. Then you make a circle element. Inside the circle element you must indicate the x and y position (cx, cy) and also the radius (r). The default color is black however you can specify other colors as shown below.

12

To change the color simply add the style argument and indicate the fill and color in quotations.

Rectangle/Square

Below is the code for making rectangles/squares. The arguments are slightly different but this should not be too challenging to figure out.

12

The x, y arguments indicate the position and the width and height arguments determine the size of the rectangle, square.

Lines & Text

Lines are another tool in d3.js. Below is the code for drawing a line.

1

2

The code should not be too hard to understand. You now need to separate coordinates. This is because the line needs to start in one place and draw until it reaches another. You can also control the color of the line and the thickness.

You can also add text using svg. In the code below we combine the line element with the text element.

12

With the text element after you set the position, font, font size, and color, you have to also add your text in-between the tags of the element.

Path

The path element is slightly trickier but also more powerful when compared to the elements we have used previously. Below is the code and output from using the path element.

12

The path element has a mini-language all to its self. “M” is where the drawing begins and is followed by the xy coordinate. “L”  draw a line. Essentially, it takes the original position and draws a line to next position. “V” indicates a vertical line. Lastly, “Z” means to close the path.

In the code below here is what it literally means

  1. Start at 40, 40
  2. Make a line from 40, 40 to 250, 40
  3. Make another line from 250, 40 to 140, 40
  4. Make a vertical line from 140,40 to 4,40
  5. Close the path

Using path can be much more complicated than this. However, this is enough for an introduction

Conclusion

This was just a teaser of what is possible with d3.js. The ability to make various graphics based on data is something that we have not even discussed yet. As such, there is much more to look forward to when using this visualization tool.

Intro to D3.js

D3.js is a JavaScript library that is useful for manipulating HTML documents. D3. js stands for Data Driven Documents JavaScript and was developed by Mike Bobstock. One of the primary purposes of D3.js is for data visualization. However, D3.js can do more than just provide data visualization as it can also allow for interaction binding, item selection, and dynamic styling of DOM (document object model) elements.

In order to use D3.js you should have a basic understanding of HTML. For data visualization you should have some idea of basic statistics and data visualization concepts in order to know what it is you  want to visualize. You also need to pick some sort of IDE so that you can manipulate your code. Lastly, you must know how to start a server on your local computer so you can see the results of your work.

In this post, we will make document that will use D3.js to make the phrase “Hello World”.

Example

Below is a bare minimum skeleton that an HTML document often has

1.png

Line 1 indicates the document type. Line 2 indicates the beginning of the html element. The html element can be used to store information about the page. Next, in line 6 is the body element. This is where the content of the web page is mostly kept. Notice how the information is contained in the various elements. All code is contained within the html element and the head and body elements are separate from one another.

First Script

We are now going to add our first few lines of d3.js code to our html document. Below is the code.

1

The code within the body element is new. In line 7-8 we are using a script element to access the d3.js library. Notice how it is a link. This means that when we run the code the d3.js library is access from some other place on the internet. An alternative to this is to download d3.js yourself. If you do this d3.js must be in the same folder as the html document that you are making.

To get d3.js from the internet you use the src argument and the place the web link in quotations. The charset argument is the setting for the character encoding. Sometimes this information  is important but it depends.

The second script element is where we actually do something with d3.js. Inside this second script element we have in line 10 the command d3.select(‘body’) this tells d3.js to select the first body element in the document. In line 11 we have the command .append(‘h1’) this tells d3.js to add an h1 heading in the body element. Lastly, we have the .text(‘Hello World’). This tells d3.js to add the text ‘Hello World’ to the h1 heading in the body element. This process of adding one command after another to modify the same object is called chaining.

When everything is done and you show your results you should see the following.

1

This is not the most amazing thing to see given what d3.js can do but it serves as an introduction.

More Examples

You are not limited to only one line of code or only one script element. Below is a more advanced version.

1.png

The new information is in lines 14-20. Lines 14-15 are just two p elements with some text. Lines 17-19 is another script element. This time we use the d3.selectAll(‘p’) which tells d3.js to apply the following commands to all p elements. In line 19 we use the .style command to set the background color to light blue. When this is done you should see the following.

1

Still not amazing, but things were modified as we wanted. Notice also that the second script element is not inside the body element. This is not necessary because you never see script elements in a website. Rather, you see the results of such a code.

Conclusion

This post introduce d3.js, which is a powerful tool for visualization. Although the examples here are fairly simple, you can be assured that there is more to this library than what has been explored so far.