D3.js - rvdegroen/notes GitHub Wiki

Table of contents

What is D3?

D3 stands for Data Driven Documents and is for creating data visualizations.It is a javascript library for manipulating documents based on data. D3 can create these visualizations with HTML, SVG's and CSS.

Why D3?

There are different tools to create your visualizations with, think about Rawgraph.io or Flourish for example, so why use the D3 library and use coding to create your visualization instead?

By using a library you have more control of what appears on the screen, rather than letting some program decide on how something will look like. You also have other libraries you can use for this, such as Chart.js or Chart.css.

D3 is more complicted than the libraries named above. On the website: www.createwithdata.com, they explain that "Chart.js provides a selection of ready to go charts which can be styled and configured while D3 offers building blocks which are combined to create virtually any data visualisation". With D3 we also want to be able to update our data.

D3 Concepts to understand

To work with D3, there are a few concepts you'll need to understand.

  1. Selections: We need to select for example all rectangles (document.querySelectorAll)
  2. Joins: We can join a dataset together with the visualization
  3. Scale: We can decide on how high or big graphs are depending on the space the chart needs
  4. Axis: You can decide on what you want to display as axis
  5. Ticks: The numbers in between axis for example (0, 5, 10)

To show you how you "use" these "concepts" of these in an example in javascript:

d3.select("#bars")
d3.selections(document.querySelectorAll("rect"))
d3.data(dataset)
d3.join("rect")

Chaining

In D3 you can chain methodes. This means that you can chain several methods together with periods (.) to perform a number of actions in a chain.

Example:

// how to select an ul
d3.select("ul")
  .append("li")
  .text("Very important item");

Scaling

Scaling in D3 means scaling your data so it proportionally looks "good" with the rest of the data.

3 Types of scales

  1. Continuous to Continuous - every number is possible in between numbrs
  2. Continuous to Discrete - Numbers inside squares (discrete data = words)
  3. Discrete to Discrete - Months to squares for example (words instead of numbers)

Methods

D3 has all sorts of methods you can use. This is my first time using the D3 library, so to make it all a bit easier for myself, I decided to write up all the methods I have learned so far, so that if I were to forget something, I can always read it back in my own words and understand it perhaps a bit easier and faster than if I were to google the same method multiple times.

Select()

The method select(), selects one element from the dom.

Example usage:

// how to select an anchor element from the HTML
const anochor = d3.select("a");

// how to select an ul
d3.select("ul")
  .append("li")
  .text("Very important item");

SelectAll()

This method is used to select a group of elements, which then returns an array of HTML elements.

Example usage:

// how to select all list elements
// if select is used, only the first li is selected
d3.selectAll("li")
   text("list item);

Append()

The method append(), appends one element to the dom.

Example usage:

// how to select an ul
d3.select("ul")
  .append("li")
  .text("Very important item");

Text()

The method text(), either sets the text of the selected element or gets the current text of the selected element. To set a value, you pass a string as argument inside the ().

Example usage:

// how to select an ul
d3.select("ul")
  .append("li")
  .text("Very important item");

Selection.text()

The text() method can take a string and a callback function as argument. To do the second thing we need the selection.text() function.

The selection.text([value]) is used to set the content of the text to a specified value of a dataset of the selected elements and replaces existing child elements.

Data()

The data() method is used on a selection of DOM elements to attach the data to those elements. The dataset is passed as an argument to the method.

Example usage:

// how to create new elements from the dataset in the DOM
const dataset = ["a", "b", "c"];
    d3.select("ul").selectAll("li")
      .data(dataset)
      .enter()
      .append("li")
      .text("New item");

Enter()

The method enter() is used to cvreate a new element in the document for a piece of data in the set.

When enter() is combines with the data() method, it looks at the selected elements and compares them to the number of data items in the set. If there are fewer elements than data items, it will create the missing elements.

Example usage:

// how to create new elements from the dataset in the DOM
const dataset = ["a", "b", "c"];
    d3.select("ul").selectAll("li")
      .data(dataset)
      .enter()
      .append("li")
      .text("New item");

React

In all of the above, I've only been talking about Javascript, but it's also possible to use the D3.js library with React. There are a few things different in React that I'll be talking about.

Components

On the website of pluralsights it stated that "React uses components as "building blocks for composing user interfaces. As such, your D3.js chart should also be modeled as a component that can be added to different parts of your website". Components can be re-used within React. React is also typically written in .jsx, like explained on the React page.

Hooks

React hooks can be used to let D3.js, interact directly with the DOM. You can use hooks like useRef or useEffect. You can also create a custom hook. By convention React hooks are prefixed with use, you when making your custom hook you should call it useSomething.

How to use D3.js with react?

On the pluralsights website you can read on how to use D3.js with React, but I'll also wrote in simple steps on how to do this (this is just from the pluralsights honestly):

  1. Create a new file named src/BarChart.jsx
  2. Copy paste the following boilerplate in that file:

// This code sets up a basic scaffold for rendering an svg with a plot area and chart axis.

import React from 'react';
import * as d3 from 'd3';

function BarChart = () => {
  return (
    <svg
      style={{
        height: 500,
        width: "100%",
        marginRight: "0px",
        marginLeft: "0px",
      }}
    >
      <g className="plot-area" />
      <g className="x-axis" />
      <g className="y-axis" />
    </svg>
  );
}

export default BarChart;

  1. You can create your custom hook. Let's make a custom hook called useD3:

import React from 'react';
import * as d3 from 'd3';

export const useD3 = (renderChartFn, dependencies) => {
    const ref = React.useRef();

    React.useEffect(() => {
        renderChartFn(d3.select(ref.current));
        return () => {};
      }, dependencies);
    return ref;
}

// This function is a hook that accepts two arguments:
// renderChartFn is a callback that contains your D3.js code to be executed
// dependencies is a fixed-length array to tell React when to run the
// renderChartFn. This is useful for preventing unnecessary re-rendering and updating the chart correctly when new data arrives.

To see how this custom hook at step 4 is used, please refer to the pluralsights website. The code is really long. Seems like a waste to paste it here, cause I doubt alot of people would read that.

Sources

⚠️ **GitHub.com Fallback** ⚠️