Skip to content

Data visualisation with D3

Whitney Abrah edited this page Nov 10, 2022 · 6 revisions

What is D3?

D3 stands for Data Driven Document. It is a javascript library for creating different interactive data visualization in the browser.

D3 is built to work with web standards namely: HTML , CSS AND SVG ( Sacalable Vecgtor Graphics). With built-in methods, data can be transformed into different charts, graphs and maps.


Methods of D3

D3 has several methods that let you add and change elements in your document.

  • The select method- Select()

    This method selects one element from the document. It also selects an argument for the name of the element you want and returns an HTML node for the first element in the document that matches the name

  • The append method - Append()

    To append means to add something to the end of a written document.

    The append method takes an argument for the element you want to add to the document.

  • The text method- text()

    The text method sets the text of the selected node or get the current text. To set the value. you will need to pass a string as an argument inside the parameter.

    it can take a string or a callback function as an argument

  • The SelectAll method- selectAll()

    The selectAll() method select a group of elements. For example you want to select all anchors in a document then you have to use this example

    const anchors = d3.selectAll("a"); - This will select all anchors in a document

  • The Data method- data()

    It is used on selected DOM elements to attach the data to the selected elements.

  • The enter method- enter()

    The enter method is to create a new element in the document for each of data in the set.

  • data()& enter()method

    With these two methods, the data focuses on the selected elements from a page and compares them to the number of the data items in the set.

Adding Inline Styling to Elements

With D3 you can add inline element by using the Style() method.

  • Style method - style()

    This methods takes a comma separated key value pair as an argument.

Example

selection.style("color"."blue")

selection.style("font-family"."verdana")


Changing styles based on Data

Call back function can be used in the 'style()' to change the styling for different elements.


Adding classes with D3

Several inline elements used on html elements becomes overwhelming and hardto manage. Using classes is one of the easy ways to style an element in a document.

  • Attribute method - attr()

    It has the same use as the style(). It takes comma separated values and can use a call back function.

Example

selection .attr("class", "conatainer"

Adding height to a bar chart

.style("height", (d) => (d + "px"))