{"id":28399475,"url":"https://github.com/learning-zone/d3js-chart-basics","last_synced_at":"2025-09-11T06:34:12.792Z","repository":{"id":107698421,"uuid":"183376343","full_name":"learning-zone/d3js-chart-basics","owner":"learning-zone","description":"D3.js Chart Basics ( v7.6.x )","archived":false,"fork":false,"pushed_at":"2022-11-30T05:45:35.000Z","size":351,"stargazers_count":21,"open_issues_count":0,"forks_count":12,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-07-08T00:15:59.035Z","etag":null,"topics":["d3-interview-questions","d3-visualization","d3js","data-analysis","data-visualization","dataset","force-layout","scale","svg","transition"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/learning-zone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-04-25T07:04:37.000Z","updated_at":"2024-08-13T05:04:55.000Z","dependencies_parsed_at":"2023-06-08T19:15:25.906Z","dependency_job_id":null,"html_url":"https://github.com/learning-zone/d3js-chart-basics","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learning-zone/d3js-chart-basics","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fd3js-chart-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fd3js-chart-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fd3js-chart-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fd3js-chart-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learning-zone","download_url":"https://codeload.github.com/learning-zone/d3js-chart-basics/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fd3js-chart-basics/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274589627,"owners_count":25312971,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-11T02:00:13.660Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["d3-interview-questions","d3-visualization","d3js","data-analysis","data-visualization","dataset","force-layout","scale","svg","transition"],"created_at":"2025-06-01T08:09:12.187Z","updated_at":"2025-09-11T06:34:12.783Z","avatar_url":"https://github.com/learning-zone.png","language":"HTML","readme":"# D3.js Chart Basics\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily ♡ welcome.*\n\n\u003cbr/\u003e\n\n## Table of Contents\n\n* *[D3.js Functions List](d3-functions-list.md)*  \n\n\u003cbr/\u003e\n\n## Q. How data binding work in d3.js?\n\nD3 includes the following important methods for data binding.\n\n|Method\t  |Description |\n|---------|--------------------|\n|data()\t  | Joins data to the selected elements|\n|enter()  |\tCreates a selection with placeholder references for missing elements|\n|exit()\t  |  Removes nodes and adds them to the exit selection which can be later removed from the DOM|\n|datum()  |\tInjects data to the selected element without computing a join.|\n\n**data():**\n\nThe data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc.\n\n```html\n\u003cbody\u003e\n    \u003cp\u003eD3 Data Binding Example \u003c/p\u003e\n\n    \u003cscript\u003e\n        var myData = [1, 2, 3, 4, 5];\n     \n         var p = d3.select(\"body\")\n                   .selectAll(\"p\")\n                   .data(myData)\n                   .text(function (d, i) {\n                        return d;\n                    });\n    \u003c/script\u003e\n\u003c/body\u003e\n```\n\n**enter():**\n\nThe enter() method dynamically creates placeholder references corresponding to the number of data values. The output of enter()can be fed to append() method and append() will create DOM elements for which there are no corresponding DOM elements on the page.\n\n```html\n\u003cbody\u003e\n\u003cscript\u003e\n    var data = [4, 1, 6, 2, 8, 9];\n    var body = d3.select(\"body\")\n                .selectAll(\"span\")\n                .data(data)\n                .enter()\n                .append(\"span\")\n                .text(function(d) { return d + \" \"; });\n\u003c/script\u003e\n\u003c/body\u003e\n```\n\n**exit():**\n\nWhile enter() is used to add new reference nodes, exit is used to remove a node.\n\n```html\n\u003cbody\u003e\n    \u003cp\u003eD3 exit Example\u003c/p\u003e\n    \u003cp\u003e\u003c/p\u003e\n    \u003cp\u003e\u003c/p\u003e\n    \u003cscript\u003e\n    \n    var myData = [\"Hello World!\"];\n\n    var p = d3.select(\"body\")\n                .selectAll(\"p\")\n                .data(myData)\n                .text(function (d, i) {\n                    return d;\n                })\n                .exit()\n                .remove();\n    \u003c/script\u003e\n\u003c/body\u003e\n```\n\n**datum():**\n\nThe datum() function is used for static visualization which does not need updates. It binds data directly to an element.\n\n```html\n\u003cbody\u003e\n    \u003cp\u003eD3 datum Example\u003c/p\u003e\n    \u003cscript\u003e\n\n    d3.select(\"body\")\n        .select(\"p\")\n        .datum(100)\n        .text(function (d, i) {\n            return d;\n        });\n    \u003c/script\u003e\n\u003c/body\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is SVG?\n\nSVG or Scalable Vector Graphics (SVG) is an XML, the markup language for determining two-dimensional vector graphics. SVG is crucial for graphics what XHTML to text.\n\n```html\n\u003c!-- Rectangle --\u003e\n\u003cdiv\u003eRectangle\u003c/div\u003e\n\u003csvg width=\"200\" height=\"200\"\u003e\n    \u003crect x=\"5\" y=\"5\" width=\"190\" height=\"190\" fill=\"#1e90ff\"\u003e\u003c/rect\u003e\n\u003c/svg\u003e\n\n\n\u003c!-- Line --\u003e\n\u003cdiv\u003eLine\u003c/div\u003e\n\u003csvg height=\"200\" width=\"200\"\u003e\n    \u003cline x1=\"0\" y1=\"0\" x2=\"200\" y2=\"200\" style=\"stroke:rgb(255,0,0);stroke-width:2\" /\u003e\n\u003c/svg\u003e\n\n\n\u003c!-- Circle --\u003e\n\u003cdiv\u003eCircle\u003c/div\u003e\n\u003csvg height=\"200\" width=\"200\"\u003e\n    \u003ccircle cx=\"100\" cy=\"100\" r=\"45\" stroke=\"#333\" stroke-width=\"2\" fill=\"orange\" /\u003e\n\u003c/svg\u003e\n\n\n\u003c!-- Text --\u003e\n\u003cdiv\u003eText\u003c/div\u003e\n\u003csvg height=\"200\" width=\"250\"\u003e\n    \u003ctext x=\"10\" y=\"120\" font-family=\"sans-serif\" font-size=\"25\" style=\"fill: #333;\"\u003eSVG Text Example\u003c/text\u003e\n\u003c/svg\u003e\n\n\n\u003c!-- Polyline --\u003e\n\u003cdiv\u003ePolyline\u003c/div\u003e\n\u003csvg height=\"200\" width=\"200\"\u003e\n    \u003cpolyline points=\"10 35, 30 10, 50 35\" stroke=\"green\" fill=\"transparent\" stroke-width=\"2\" /\u003e\n\u003c/svg\u003e\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/a.svg.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between canvas and SVG in d3.js?\n\nSVG is abbreviated as **Scalable Vector Graphics**. It is a vector-based graphics and used the XML based format for graphics providing the support for interaction. SVG images are way better than bitmap images.  In SVG images, the vector image is composed of a fixed set of shapes and while scaling these images it preserves the shape of the image.\n\nCanvas is an HTML element, which is used to draw graphics on the web page. It is referred to as a bitmap with an immediate mode graphics application programming interface. For drawing on it. The element canvas is used as a container for graphics. In Canvas, we need the script to draw the graphics.\n\n```html\n\u003ccanvas id=\"myCanvas\" width=\"800\" height=\"800\"\u003e\u003c/canvas\u003e\n```\n\n```js\nvar canvas = document.getElementById('myCanvas');\nvar context = canvas.getContext('2d');\ncontext.fillStyle = '#c00';\ncontext.fillRect(10, 10, 100, 100);\n```\n\n**Canvas vs SVG in D3:**\n\nWith SVG, data binding is easy - we can assign a datum to an individual svg element and then use that datum to set its attributes/update it/etc. This is built upon the statefulness of svg - we can re-select a circle and modify it or access its properties.\n\nWith Canvas, canvas is stateless, so we can\\'t bind data to shapes within the canvas as the canvas only comprises of pixels. As such we can\\'t select and update elements within the canvas because the canvas doesn\\'t have any elements to select.\n\nIn D3js the `enter`/`update`/`exit` cycle (or basic append statements) are needed for svg in idiomatic D3: we need to enter elements to see them and we style them often based on their datum. With canvas, we don\\'t need to enter anything, same with `exiting`/`updating`. There are no elements to append in order to see, so we can draw visualizations without the `enter`/`update`/`exit` or the append/insert approaches used in d3 svg visualizations.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain selections in d3.js?\n\nD3 Selections allow data-driven transformation of the document object model (DOM): set attributes, styles, properties, HTML or text content, etc. Using the data join\\'s enter and exit selections, you can also add or remove elements to correspond to data.\n\n|Method\t                    |Description |\n|---------------------------|---------------------------------------------------------------------------------------|\n|d3.select(css-selector)\t|Returns the first matching element in the HTML document based on specified css-selector|\n|d3.selectAll(css-selector)\t|Returns all the matching elements in the HTML document based on specified css-selector|\n\n*Example:*\n\n```html\n\u003cdiv class=\"container\"\u003e\n    \u003ch2\u003eSelect DOM Elements using D3\u003c/h2\u003e\n    \u003csection id=\"chart\"\u003e\n        \u003cdiv class=\"item\"\u003eBarot Bellingham\u003c/div\u003e\n        \u003cdiv class=\"item\"\u003eHassum Harrod\u003c/div\u003e\n        \u003cdiv class=\"item\"\u003eJennifer Jerome\u003c/div\u003e\n        \u003cdiv class=\"item\"\u003eRichard Tweet\u003c/div\u003e\n        \u003cdiv class=\"item\"\u003eLorenzo Garcia\u003c/div\u003e\n        \u003cdiv class=\"item\"\u003eXhou Ta\u003c/div\u003e\n    \u003c/section\u003e\n\u003c/div\u003e\n```\n\n```js\n    d3.selectAll('.item:nth-child(2n)')\n            .style(\"color\", \"green\");\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/b.selection.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain about d3.js Scales?\n\nD3.js provides scale functions to perform data transformations. These functions map an input domain to an output range. D3 provides the following scaling methods for different types of charts.\n\n|Scale Type  |\tMethod\t          |   Description |\n|------------|------------------- |----------------|\n|Continuous\t |d3.scaleLinear()    |Construct continuous linear scale where input data (domain) maps to specified output range.|\n|            |d3.scaleIdentity()  |Construct linear scale where input data is the same as output.|\n|            |d3.scaleTime()\t  |Construct linear scale where input data is in dates and output in numbers.|\n|            |d3.scaleLog()\t      |Construct logarithmic scale.|\n|            |d3.scaleSqrt()\t  |Construct square root scale.|\n|            |d3.scalePow()\t      |Construct exponential scale.|\n|Sequential\t |d3.scaleSequential()|Construct sequential scale where output range is fixed by interpolator function.|\n|Quantize\t |d3.scaleQuantize()  |Construct quantize scale with discrete output range.|\n|Quantile\t |d3.scaleQuantile()  |Construct quantile scale where input sample data maps to discrete output range.|\n|Threshold\t |d3.scaleThreshold() |Construct scale where arbitrary input data maps to discrete output range.|\n|Band\t     |d3.scaleBand()\t  |Band scales are like ordinal scales except the output range is continuous and numeric.|\n|Point\t     |d3.scalePoint()\t  |Construct point scale.|\n|Ordinal\t |d3.scaleOrdinal()\t  |Construct ordinal scale where input data includes alphabets and are mapped to discrete numeric output range.|\n\nExample\n\n```html\n\u003cdiv class=\"container\"\u003e\n    \u003ch1\u003eD3 Color Scales\u003c/h1\u003e\n    \u003cdiv id=\"chart\"\u003e\u003c/div\u003e\n\u003c/div\u003e\n```\n\n```js\nvar bardata = [90, 45, 25, 15, 10, 7];\n     \nvar height = 400,\n    width = 600,\n    barWidth = 50,\n    barOffset = 5;\n\nvar colors = d3.scale.linear()\n    .domain([0, bardata.length])\n    .range(['#C61C6F', '#B58929']);\n\nvar yScale = d3.scale.linear()\n    .domain([0, d3.max(bardata)])\n    .range([0, height]);\n\nvar xScale = d3.scale.ordinal()\n    .domain(d3.range(0, bardata.length))\n    .rangeBands([0, width]);\n\nd3.select('#chart').append('svg')\n    .attr('width', width)\n    .attr('height', height)\n    .style('background', '#C9D7D6')\n    .selectAll('rect').data(bardata)\n    .enter().append('rect')\n    .style('fill', function (d, i) {\n        return colors(i);\n    })\n    .attr('width', xScale.rangeBand() - 10)\n    .attr('height', function (d) {\n        return yScale(d);\n    })\n    .attr('x', function (d, i) {\n        return xScale(i);\n    })\n    .attr('y', function (d) {\n        return height - yScale(d);\n    });\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/i.scales.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the slider available in d3.js?\n\nThe slider available in d3.js are\n\n* Default slider\n\n```js\nd3.slider()\n```\n\n* Slider with start value\n\n```js\nd3.slider().value(25)\n```\n\n* Slider with slide event\n\n```js\nd3.slider().on(\"slide\", function(evt, value) {\n  d3.select('#slider3text').text(value);\n})\n```\n\n* Slider with default axis\n\n```js\nd3.slider().axis(true)\n```\n\n* Slider with custom axis\n\n```js\nd3.slider().axis( d3.svg.axis().orient(\"top\").ticks(6) )\n```\n\n* Slider with min, max, and step values\n\n```js\nd3.slider().axis(true).min(2000).max(2100).step(5)\n```\n\n* Vertical Slider\n\n```js\nd3.slider().value(50).orientation(\"vertical\")\n```\n\n**Example:**\n\n```html\n\u003cp id=\"value\"\u003e\u003c/p\u003e\n\u003cdiv id=\"slider\"\u003e\u003c/div\u003e\n```\n\n```js\nvar slider = d3\n    .sliderHorizontal()\n    .min(0)\n    .max(10)\n    .step(1)\n    .width(300)\n    .displayValue(false)\n    .on('onchange', val =\u003e {\n      d3.select('#value').text(val);\n    });\n\n  d3.select('#slider')\n    .append('svg')\n    .attr('width', 500)\n    .attr('height', 100)\n    .append('g')\n    .attr('transform', 'translate(30,30)')\n    .call(slider);\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/slider.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between domain, range and scale in d3.js?\n\n**Domain:**\n\n```js\nD for Domain, D for Data.\n```\n\nDomain represents the boundaries within which your data lies. e.g. If I had an array of numbers with no number smaller than 1 and no number larger than 100, my domain would be 1 to 100.\n\n**Range**  \nYou usually make use of a range when you want to transform the value of a raw data point into a corresponding pixel coordinate.\n\n**Scale**  \nNow that you know what a domain and range is, you need a way to convert your data into corresponding values in the domain. And thats exactly what scales do.\n\nThe most common types of scales are – quantitative scales and ordinal scales.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the role of “Path Data Generator” in d3.js?\n\nD3.js includes a set of Path Data Generators helper classes for generating SVG Path instructions.\n\n```js\nd3.svg.line()\n```\n\nPath generator includes\n\n* `d3.svg.line()` - create a new line generator\n* `d3.svg.line.radial()` - create a new radial line generator\n* `d3.svg.area()` - create a new area generator\n* `d3.svg.area.radial()` - create a new radial area generator\n* `d3.svg.arc()` - create a new arc generator\n* `d3.svg.symbol()` - create a new symbol generator\n* `d3.svg.chord()` - create a new chord generator\n* `d3.svg.diagonal()` - create a new diagonal generator\n* `d3.svg.diagonal.radial()` - create a new radial diagonal generator\n\n*Example:*\n\n```js\n//The data for our line\nvar lineData = [ { \"x\": 1,   \"y\": 5},  { \"x\": 20,  \"y\": 20},\n                 { \"x\": 40,  \"y\": 10}, { \"x\": 60,  \"y\": 40},\n                 { \"x\": 80,  \"y\": 5},  { \"x\": 100, \"y\": 60}];\n\n//This is the accessor function we talked about above\nvar lineFunction = d3.svg.line()\n                         .x(function(d) { return d.x; })\n                         .y(function(d) { return d.y; })\n                         .interpolate(\"linear\");\n\n//The SVG Container\nvar svgContainer = d3.select(\"body\").append(\"svg\")\n                                    .attr(\"width\", 200)\n                                    .attr(\"height\", 200);\n\n//The line SVG Path we draw\nvar lineGraph = svgContainer.append(\"path\")\n                            .attr(\"d\", lineFunction(lineData))\n                            .attr(\"stroke\", \"blue\")\n                            .attr(\"stroke-width\", 2)\n                            .attr(\"fill\", \"none\");\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What d3.js enter method does?\n\nD3.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.\n\n```js\nvar numbers = [15, 8, 42, 4, 32];\n```\n\nWhen 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Mention the command used to create simple axis in d3.js?\n\nThe command to create simple axis in d3.js is\n\n```js\nvar xAxis = d3.svg.axis().\n```\n\n|Axis Method\t |               Description          |\n|----------------|------------------------------------|\n|d3.axisTop()\t |Creates top horizontal axis.        |\n|d3.axisRight()\t |Creates vertical right-oriented axis.|\n|d3.axisBottom() |Creates bottom horizontal axis.      |\n|d3.axisLeft()\t |Creates left vertical axis.          |\n\n*Example:*\n\n```html\n\u003cdiv class=\"container\"\u003e\n    \u003ch1\u003eAxes in D3\u003c/h1\u003e\n    \u003cdiv id=\"chart\"\u003e\u003c/div\u003e\n\u003c/div\u003e\n```\n\n```js\nvar width = 500, height = 500;\nvar data = [10, 20, 30, 40, 50];\nvar svg = d3.select(\"body\")\n    .append(\"svg\")\n    .attr(\"width\", width)\n    .attr(\"height\", height);\n\nvar xscale = d3.scaleLinear()\n    .domain([0, d3.max(data)])\n    .range([0, width - 100]);\n\nvar yscale = d3.scaleLinear()\n        .domain([0, d3.max(data)])\n        .range([height/2, 0]);\n\nvar x_axis = d3.axisBottom()\n        .scale(xscale);\n\nvar y_axis = d3.axisLeft()\n        .scale(yscale);\n    svg.append(\"g\")\n       .attr(\"transform\", \"translate(50, 10)\")\n       .call(y_axis);\n\nvar xAxisTranslate = height/2 + 10;\n    svg.append(\"g\")\n       .attr(\"transform\", \"translate(50, \" + xAxisTranslate  +\")\")\n       .call(x_axis);\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/j.axis.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is SVG group element?\n\nSVG group element is used to group SVG element together; each SVG group element is a container which consists of child SVG elements.  It is defined by `\u003cg\u003e` and `\u003c/g\u003e`.\n\n## Q. How to apply multiple classes at once in D3?\n\nTo set multiple classes at once you can use the object literal as\n\n```js\nselection.classed({ 'foo':true, 'bar': false})\n```\n\n## Q. What is a transition in d3.js?\n\nTransition in d3.js gradually interpolate attributes and styles over time, transition is used for animation purpose.  It is based on only two key frames, start, and end.  The starting key frame defines the current state of the DOM, while the ending key frame is a set of styles, attributes and other properties specified.\n\n|Method\t               |Description                                           |\n|----------------------|------------------------------------------------------|\n|selection.transition()|this schedules a transition for the selected elements |\n|transition.duration() |duration specifies the animation duration in milliseconds for each element |\n|transition.ease()\t   |ease specifies the easing function, example: linear, elastic, bounce |\n|transition.delay()\t   |delay specifies the delay in animation in milliseconds for each element |\n\n*Example:*\n\n```html\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cstyle\u003e\n        #container {\n            height: 100px;\n            width: 100px;\n            background-color: black;\n\n        }\n    \u003c/style\u003e\n\u003cscript src=\"https://d3js.org/d3.v4.min.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cdiv id=\"container\"\u003e\u003c/div\u003e\n\u003cscript\u003e\n    d3.select(\"#container\")\n      .transition()\n      .duration(1000)\n      .style(\"background-color\", \"red\");\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n[Live Example](https://learning-zone.github.io/d3js-interview-questions/s.transitions.html)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the command to interpolate two objects in d3.js?\n\nTo 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.\n\n## Q. What is the command “d3.ascending (a, b)” is used?\n\nThis 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.\n\n## Q. How XML file is called in d3.js?\n\nBy using the command `d3.xml(url[mimeType][,callback])` XML file can be called. This command will create a request for\nthe XML file at the specified url. If a call back is declared, the request will be immediately processed with the GET method and the call back will be invoked when the file is loaded, or request fails.\n\n## Q. What happens if no call back is specified for XML file in d3.js?\n\nIf no call back is specified, the returned request can be issued using xhr.get and handled using xhr.on.\n\n## Q. Mention the command to join the specified array of data in d3.js?\n\nTo join the specified array of data in d3.js you can use the command `selection.data([values[,key]])`.  The values here specifies the data for each group in the selection while a key function determines how data is connected to elements.\n\n## Q. What does the command d3.csv.parseRows(string[,accessor]) ?\n\nThis command parses the specified string, which is the content of a CSV file, returning an array of arrays representing the parsed rows.\n\n## Q. What is the use of “Enter” and “Exit” selection in d3.js?\n\nBy using `enter()` and `exit()` selection in d3.js, you can create new nodes for incoming data and eliminate outgoing nodes that are no longer required.\n\n## Q. What is the best way to create the stacked barchart using d3.js?\n\n```js\nvar data = [\n  {\"ORDER\": 1, \"apples\": 3840, \"bananas\": 1920, \"cherries\": 960},\n  {\"ORDER\": 2, \"apples\": 1600, \"bananas\": 1440, \"cherries\": 960},\n  {\"ORDER\": 3, \"apples\":  640, \"bananas\":  960, \"cherries\": 640},\n  {\"ORDER\": 4, \"apples\":  320, \"bananas\":  480, \"cherries\": 640}\n];\n\nvar h = 200;\nvar w = 200;\nvar svg = d3.select('body').append('svg').attr('width',w).attr('height',h);\nvar g = svg.append('g');\n\n\nvar x = d3.scaleBand().rangeRound([0, w-50]);\nvar y = d3.scaleLinear().range([h-50, 0]).domain([0,10000]);\nvar color = ['#bae4bc','#7bccc4','#43a2ca'];\n\nvar stack = d3.stack()\n    .keys([\"apples\", \"bananas\", \"cherries\"])\n    .order(d3.stackOrderNone)\n    .offset(d3.stackOffsetNone);\n    \nvar series = stack(data);\n\nx.domain(data.map(function(d) { return d.ORDER; }));\n\ng.append(\"g\")\n    .selectAll(\"g\")\n    .data(series)\n    .enter().append(\"g\")\n        .attr(\"fill\", function(d,i) { return color[i]; })\n    .selectAll(\"rect\")\n    .data(function(d) { return d; })\n    .enter().append(\"rect\")\n        .attr(\"x\", function(d) { return x(d.data.ORDER); })\n        .attr(\"y\", function(d) { return y(d[1]); })\n        .attr(\"height\", function(d) { return y(d[0]) - y(d[1]); })\n        .attr(\"width\", x.bandwidth());\n\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between d3.scale.linear() and d3.scaleLinear()?\n\n**version 3: d3.scale.linear()**  \nConstructs a new linear scale with the default domain [0,1] and the default range [0,1]. Thus, the default linear scale is equivalent to the identity function for numbers; for example linear(0.5) returns 0.5.\n\n**version 4: d3.scaleLinear()**  \nConstructs a new continuous scale with the unit domain [0, 1], the unit range [0, 1], the default interpolator and clamping disabled. Linear scales are a good default choice for continuous quantitative data because they preserve proportional differences. Each range value y can be expressed as a function of the domain value x: y = mx + b.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set initial zoom level in d3.js?\n\n**D3v4:**\n\n```js\nvar zoom = d3.zoom().on(\"zoom\", zooming);\n\nvis = svg.append(\"svg:svg\")\n     .attr(\"width\", width)\n     .attr(\"height\", height)\n     .call(zoom) // here\n     .call(zoom.transform, d3.zoomIdentity.translate(100, 50).scale(0.5))\n     .append(\"svg:g\")\n     .attr(\"transform\",\"translate(100,50) scale(.5,.5)\");\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to resize an SVG when the window is resized in d3.js?\n\n```css\n.svg-container {\n  display: inline-block;\n  position: relative;\n  width: 100%;\n  padding-bottom: 100%; /* aspect ratio */\n  vertical-align: top;\n  overflow: hidden;\n}\n.svg-content-responsive {\n  display: inline-block;\n  position: absolute;\n  top: 10px;\n  left: 0;\n}\n\nsvg .rect {\n  fill: gold;\n  stroke: steelblue;\n  stroke-width: 5px;\n}\n```\n\n```html\n\u003cscript src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"\u003e\u003c/script\u003e\n\u003cdiv id=\"chartId\"\u003e\u003c/div\u003e\n```\n\n```js\nd3.select(\"div#chartId\")\n   .append(\"div\")\n   // Container class to make it responsive.\n   .classed(\"svg-container\", true) \n   .append(\"svg\")\n   // Responsive SVG needs these 2 attributes and no width and height attr.\n   .attr(\"preserveAspectRatio\", \"xMinYMin meet\")\n   .attr(\"viewBox\", \"0 0 600 400\")\n   // Class to make it responsive.\n   .classed(\"svg-content-responsive\", true)\n   // Fill with a rectangle for visualization.\n   .append(\"rect\")\n   .classed(\"rect\", true)\n   .attr(\"width\", 600)\n   .attr(\"height\", 400);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to get mouse position in d3.js?\n\n```js\nvar svg = d3.select('body').append('svg')\n    .attr('width', width)\n    .attr('height', height)\n    .on('mousemove', function() {\n      console.log( d3.event.clientX, d3.event.clientY ) // log the mouse x,y position\n    });\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to format the date in d3.js?\n\n```js\n\u003e formatDate = d3.time.format(\"%b-%Y\")\n\u003e formatDate(parseDate('2020-01-01'))\n\"Jan-2020\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to calculate the area of the polygon in d3.js?\n\nThe `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.\n\n```js\nvar d = [\n  [-1, 415.44],\n  [146.93, 304.47],\n  [195.45, 152.13],\n  [-1, 134.64]\n];\n\nvar area = d3.polygonArea(d);\n\nconsole.log(area) // Output: 36157.2759\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to handle events in d3.js?\n\nThe `on()` method adds an event listener to all selected DOM elements.\n\nSyntax\n\n```js\nd3.selection.on(type[, listener[, capture]]);\n```\n\nThe 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.\n\nThe following table lists important event handling method and objects.\n\n|Event Methods\t      |Description                                                                                |\n|---------------------|-------------------------------------------------------------------------------------------|\n|selection.on()\t      |  Add or remove event listeners to capture event types like click, mouseover, mouseout etc.|\n|selection.dispatch() |\tCaptures event types like click, mouseover, mouseout. Typenames is the eventname, listener is the event listener |\n|d3.event\t          | Event object to access standard event fields such as timestamp or methods like preventDefault|\n|d3.mouse(container)  |Gets the x and y coordinates of the current mouse position in the specified DOM element.|\n|d3.touch()\t          | Gets the touch coordinates to a container|\n\n*Example:* Event Handling\n\n```html\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cstyle\u003e\n        div {\n            height: 100px;\n            width: 100px;\n            background-color: steelblue;\n            margin: 5px;\n        }\n    \u003c/style\u003e\n    \u003cscript src=\"https://d3js.org/d3.v4.min.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cdiv\u003e \u003c/div\u003e\n\u003cscript\u003e\n    d3.selectAll(\"div\")\n      .on(\"mouseover\", function(){\n          d3.select(this)\n            .style(\"background-color\", \"orange\");\n\n          // Get current event info\n          console.log(d3.event);\n\n          // Get x \u0026 y co-ordinates\n          console.log(d3.mouse(this));\n      })\n      .on(\"mouseout\", function(){\n          d3.select(this)\n            .style(\"background-color\", \"steelblue\")\n      });\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fd3js-chart-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearning-zone%2Fd3js-chart-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fd3js-chart-basics/lists"}