Google News
logo
D3.js Interview Questions
 
D3.js includes a set of Path Data Generators helper classes for generating SVG Path instructions.
d3.svg.line()
Path generator includes
 
* d3.svg.line() - create a new line generator
* d3.svg.line.radial() - create a new radial line generator
* d3.svg.area() - create a new area generator
* d3.svg.area.radial() - create a new radial area generator
* d3.svg.arc() - create a new arc generator
* d3.svg.symbol() - create a new symbol generator
* d3.svg.chord() - create a new chord generator
* d3.svg.diagonal() - create a new diagonal generator
* d3.svg.diagonal.radial() - create a new radial diagonal generator

Example :
//The data for our line
var lineData = [ { "x": 1,   "y": 5},  { "x": 20,  "y": 20},
                 { "x": 40,  "y": 10}, { "x": 60,  "y": 40},
                 { "x": 80,  "y": 5},  { "x": 100, "y": 60}];

//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
                         .x(function(d) { return d.x; })
                         .y(function(d) { return d.y; })
                         .interpolate("linear");

//The SVG Container
var svgContainer = d3.select("body").append("svg")
                                    .attr("width", 200)
                                    .attr("height", 200);

//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
                            .attr("d", lineFunction(lineData))
                            .attr("stroke", "blue")
                            .attr("stroke-width", 2)
                            .attr("fill", "none");
D3.js enter method returns the virtual enter selection from the data operator. This method is only applicable to Data Operator as such data operator is the only one that returns three virtual selections.
var numbers = [15, 8, 42, 4, 32];
When our dataset contains more items than there are available DOM elements, the surplus data items are stored in a sub set of this selection called the enter selection.
The on() method adds an event listener to all selected DOM elements.
 
Syntax : 
d3.selection.on(type[, listener[, capture]]);
The first parameter is an event type as string such as "click", "mouseover" etc. The second parameter is a callback function which will be executed when an event occurs and the third optional parameter capture flag may be specified.
 
The following table lists important event handling method and objects.

Event Methods Description
selection.on() Add or remove event listeners to capture event types like click, mouseover, mouseout etc.
selection.dispatch() Captures event types like click, mouseover, mouseout. Typenames is the eventname, listener is the event listener
d3.event Event object to access standard event fields such as timestamp or methods like preventDefault
d3.mouse(container) Gets the x and y coordinates of the current mouse position in the specified DOM element.
d3.touch() Gets the touch coordinates to a container

Example : Event Handling
<!doctype html>
<html>
<head>
    <style>
        div {
            height: 100px;
            width: 100px;
            background-color: steelblue;
            margin: 5px;
        }
    </style>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div> </div>
<script>
    d3.selectAll("div")
      .on("mouseover", function(){
          d3.select(this)
            .style("background-color", "orange");

          // Get current event info
          console.log(d3.event);

          // Get x & y co-ordinates
          console.log(d3.mouse(this));
      })
      .on("mouseout", function(){
          d3.select(this)
            .style("background-color", "steelblue")
      });
</script>
</body>
</html>
> formatDate = d3.time.format("%b-%Y")
> formatDate(parseDate('2020-02-02'))
"Feb-2020"
The d3.polygonArea() method returns the signed area of the specified polygon. If the vertices of the polygon are in counterclockwise order (assuming a coordinate system where the origin ⟨0,0⟩ is in the top-left corner), the returned area is positive; otherwise it is negative, or zero.
 
var d = [
  [-1, 415.44],
  [146.93, 304.47],
  [195.45, 152.13],
  [-1, 134.64]
];

var area = d3.polygonArea(d);

console.log(area) // Output: 36157.2759
var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height)
    .on('mousemove', function() {
      console.log( d3.event.clientX, d3.event.clientY ) // log the mouse x,y position
    });
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="chartId"></div>
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
D3v4
var zoom = d3.zoom().on("zoom", zooming);

vis = svg.append("svg:svg")
     .attr("width", width)
     .attr("height", height)
     .call(zoom) // here
     .call(zoom.transform, d3.zoomIdentity.translate(100, 50).scale(0.5))
     .append("svg:g")
     .attr("transform","translate(100,50) scale(.5,.5)");
To interpolate two objects in d3.js command d3.interpolateObject(a,b) is used. Object interpolation is useful particularly for data space interpolation, where data is interpolated rather than attribute values.
This command is comparator function that is used for a natural order, and can be used along with the built-in-array sort method to arrange elements in ascending order.