D3.js : SELECTION

I am totally newbie in D3, so don’t expect me to share an advance tutorial for D3 XD I am still learning and this post would just be my another self-notes, wherever or whenever i need it :’)

This would be my first post about D3, and i just wanna share about what i think it’s important if you wanna start learning D3. Well, actually when i first try it, just look at the library, check the examples, download the code and try to run it inside my project. And it works fine. But, when i wanna go deeper about D3, like, you know, start to customize the view, i need to learn more about it and what i got first, i think about it’s Selection; I think it’s an important thing since to modify element, syling or adding event/action, i need to learn how i make selection to the element i want first.

Well, i’m not start by ‘how to make the chart/element’ bcz, as you know, i just download some chart already on github or bl.ocks.org/d3indepth XD sorry. But if you interested, you can visit this helpfull article right here : https://www.dashingd3js.com/

Okay, so we’ll start. I am already make the graph, like forced-directed graph, consist of nodes and links (the line to connect the nodes). And, i start to customize it. D3 selections allow DOM elements to be selected in order to do something with them, be it changing style, modifying their attributes, performing data-joins or inserting/removing elements. (http://d3indepth.com/selections/) – btw you should visit the site, it really helpful. In D3 we use SVG element.

Scalable Vector Graphics (SVG)

Scalable Vector Graphics (SVG) is a family of specifications for creating two-dimensional vector graphics. Vector graphics are not created out of pixels. Vector graphics are created with paths having a start and end point, as well as points, curves and angles in between. Since Vector Graphics are not created out of pixels, they can be scaled up to larger or smaller sizes without losing image quality.

SVG images and their behaviors are defined in XML text files. The XML text can be included in an HTML document. This text means that images can be created and edited in a text editor. Also, since the DOM includes XML as part of the DOM specification, we can use the DOM Tree to access and update the structure, content and style of SVG Images.

SVG comes with a basic set of shape elements:

  • Rectangle
  • Circle
  • Ellipse
  • Straight Line
  • Polyline
  • Polygon

Okay, i already make a force-directed-graph that looks like this :

D3 – forced network

Okay, it’s only circles (nodes) and links btw. But if you learn D3, you will need to check the element inspector ( i prefer use chrome). Why? Because it will help us to make selection. As you see on D3, we just write code like this :

var svg = d3.select("svg"),
width = +svg.attr("width"), height = +svg.attr("height");  

var node = g.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes_data)
.enter()
.append("circle")
.attr("r", radius)
.attr("fill", circleColour);

and the result is as you can see above ( on the picture), but then we check inspector, and we got like this :

circle d3

Elements

You can see the <g> tag , it is the SVG Group Element is a container that contains all child SVG elements defined inside of it and that share the same attribute. In the example, it have 2 groups. One contains lines and the others contain circles. And there’s many circle elements that created with D3, we use .append("circle")and its populate the element as we can see in the element inspector.

D3 has two functions to make selections d3.select and d3.selectAll.

d3.select selects the first matching element whilst d3.selectAll selects all matching elements. Each function takes a single argument which specifies the selector string. Examples, we want to select all the circles, we can use d3.selectAll(“circle”); And when we use d3.select(“circle”); it will select the first matching element, only one, the first one. In my example, it is the line that i blocked. We can also select item by it class like d3.selectAll(“.classname”);

We can also updating the elements with functions, like this :

d3.selectAll('circle')
  .attr('cx', function(d, i) {
    return i * 100;
  });

The function typically accepts two arguments d and i. The first argument d is the joined data and i is the index of the element within the selection. If we want to update elements in a selection according to their position within the selection, we can use the iargument. For example to position some rect elements horizontally we can use: (http://d3indepth.com/selections/)

When i added events,  i add a function and i want to change radius of the element i clicked (for example) i can use “this“, so it will look like :

d3.select(this); and i can also modify element, like d3.select(this).attr('radius', 10);

d3 styling change radius

d3 styling change radius

We can also make selection like this:

// Add .selected class to 3rd circle
d3.select('circle:nth-child(3)')
	.classed('selected', true);

// Set checked property of checkbox
d3.select('input.robot-checkbox')
	.property('checked', true);

So it will just modify the element clicked, and change radius to 10.  You can also adding text, title, or changing the color, add borders etc, but i will write more about modifying element and styling on my next post ! See youu very sooon 🙂

D3.js : Modifying Elements

After selecetion, i would like to share about styling in D3.js. Modifying element atribut like change the circle radius, color, width, stroke, fill color etc, it means we change the style, so i called it styling.

I will make it so simple, so i have a circle like this :

var svg = d3.select(“svg”),
width = +svg.attr(“width”),
height = +svg.attr(“height”);

svg.append(“circle”) // attach a circle
.attr(“cx”, 200) // position the x
.attr(“cy”, 100) // position the y
.attr(“r”, 50) // set the radius
.style(“fill”, “red”); // set the fill

 

There’s some atribut  like x and y position, the radius and fill color. If we want no color just add .style(“fill”, “none”). And we can also add color like  (.style("fill", "rgb(255,0,0)");) or in hexadecimal (.style("fill", "#f00");)

Styles in D3:

  • fill
  • stroke
  • opacity
  • fill-opacity
  • stroke-opacity
  • stroke-width
  • stroke-dassharay
  • stroke-linecap
  • stroke-linejoin
  • writing-mode
  • glyph-orientation-vertical

I added some styles to the circle, and then it look like this :

 

d3.select(“circle”) // select a circle
.attr(“cx”, 200) // position the x
.attr(“cy”, 100) // position the y
.attr(“r”, 50) // set the radius
.style(“fill”, “red”) // set the fill colour
.style(“fill-opacity”, 0.4) // set fill opacity
.style(“stroke”, “blue”) // set the line color
.style(“stroke-width”, 3 ) // set the line width
.style(“stroke-dasharray”, (“10,3”)) // make the stroke dashed

Then, i tried to make lines and add some styles, looks like this:

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “butt”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 50) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 50); // y position of the second end of the line

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “round”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 100) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 100); // y position of the second end of the line

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “square”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 150) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 150); // y position of the second end of the line

Attrributes in D3:

      • xy ;
        Using the x and y attributes places the anchor points for these elements at a specified location. Of the elements that we have examined thus far, the rectangle element and the text element have anchor points to allow them to be positioned
      • x1x2y1y2

        • x1: The x position of the first end of the line as measured from the left of the screen.
        • y1: The y position of the first end of the line as measured from the top of the screen.
        • x2: The x position of the second end of the line as measured from the left of the screen.
        • y2: The y position of the second end of the line as measured from the top of the screen.
      • points
        The points attribute is used to set a series of points which are subsequently connected with a line and / or which may form the bounds of a shape. These are specifically associated with the polyline and polygonelements. Like the xy and x1x2y1y2 attributes, the coordinates are set from the top, left hand corner of the web page.
        The data for the points is entered as a sequence of x,y points in the following format;
        .attr("points", "100,50, 200,150, 300,50");
      • cxcy

        The cxcy attributes are associated with the circle and ellipse elements and designate the centre of each shape. The coordinates are set from the top, left hand corner of the web page.
        • cx: The position of the centre of the element in the x axis measured from the left side of the screen.
        • cy: The position of the centre of the element in the y axis measured from the top of the screen.
      • r, to set radius of the element
        .attr("5", "50");
      • rx, ry
        The rxry attributes are associated with the ellipse element and designates the radius in the x direction (rx) and the radius in the y direction (ry).
        • rx: The radius of the ellipse in the x dimension from the cxcy position to the perimeter of the ellipse.
        • ry: The radius of the ellipse in the y dimension from the cxcy position to the perimeter of the ellipse.
        • translate: Where the element is moved by a relative value in the x,y direction.
        • scale: Where the element’s attributes are increased or reduced by a specified factor.
        • rotate: Where the element is rotated about its reference point by an angular value.transform (translate(x,y), scale(k), rotate(a)) 
          The transform attribute is a powerful one which allows us to change the properties of an element in several different ways.
          .attr("transform", "translate(50,50)") // translate the circle
          .attr("transform", "scale(2)"); // scale the circle attributes

          The translate-rotate attribute will rotate an element and its attributes by a declared angle in degrees.

          svg.append("text") // append text
          .style("fill", "black") // fill the text with the colour black .attr("x", 200) // set x position of left side of text
          .attr("y", 100) // set y position of bottom of text
          .attr("dy", ".35em") // set offset y position .attr("text-anchor", "middle") // set anchor y justification .attr("transform", "rotate(10)") .text("Hello World"); // define the text to display
      • widthheight 

        width and height are required attributes of the rectangle element. width designates the width of the rectangle and height designates the height (If you’re wondering, I often struggle defining the obvious).

      • text-anchor

        The text-anchor attribute determines the justification of a text element
        Text can have one of three text-anchor types;
        • start where the text is left justified.
        • middle where the text is centre justified.
        • end where the text is right justified
      • dxdy
        dx and dy are optional attributes that designate an offset of text elements from the anchor point in the x and y dimension . There are several different sets of units that can be used to designate the offset of the text from an anchor point. These include em which is a scalable unit, px (pixels), pt (points (kind of like pixels)) and %(percent (scalable and kind of like em))
      • lenghtAdjust

        The lengthAdjust attribute allows the textLength attribute to have the spacing of a text element controlled to be either spacing or spacingAndGlyphs;
        • spacing: In this option the letters remain the same size, but the spacing between the letters and words are adjusted.
        • spacingAndGlyphs: In this option the text is stretched or squeezed to fit
      • textLength
        The textLength attribute adjusts the length of the text to fit a specified value.

And also i have summaries :

Source :

http://www.d3noob.org/2014/02/styles-in-d3js.html

http://www.d3noob.org/2014/02/attributes-in-d3js.html

http://www.tutorialsteacher.com/d3js

It’s a very useful site btw, i highly recommend you to visit the site if you wanna learn about D3 (as beginner). But so sad that the last post on that site in 2016. There’s some version D3, try the latest (V4)