DEV Community


My Journey Using D3

vicradon profile image Osinachi Chukwujama ・2 min read

So, I recently decided to explore the D3 library, and of course, I was using freecodecamp. D3 sounds like an awesome front end library which enables you do things from manipulating your DOM elements to creating visualizations using SVG and Canvas. From what I've seen so far it's an awesome library.

To use it, all you need is to reference the script from a CDN or include it in your project. Just one script, no configurations. Well, for now...

An Example Then

Ok, the most basic thing you can do with this library is to manipulate DOM elements

      .text("Hello D3");

Here, we used D3's select() method to select the body element. Then add a h1 node and and the text "Hello D3" to that node.

A more involved example would be

    const dataset = [12, 31,22,17, 25, 18, 29, 14, 9];"body")
      .text("New Title")

Here, the library selects the body tag and selects all h2 elements in it. It then gets data from the array called dataset. The enter method then enters each array item into the DOM tree, where new

tags are added with innerText called "New Title". Here, d3 actually selects elements that don't exist yet and appends text to them based on data

How Cool Can it get?

Very cool infact. You can use JS functions, conditions, callbacks to apply styles to elements. In this simple example, we would add style conditionally based on magnitude of values.

    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];"body").selectAll("h2") //h2 elements which don't exist yet
      .append("h2")    //now they do
      .text((d) => (d + " USD"))
      .style("color", d => d < 20 ? "red" : "green")

And the output is...
The output

A simple bar chart.

Let's create a simple bar chart using data in an array and CSS styling

  .bar {
    width: 25px;
    height: 100px;
    margin: 2px;
    display: inline-block;
    background-color: cornflowerblue;
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];"body").selectAll("div")
      .attr("class", "bar")
      .style("height", d => d * 10 + "px")

Here, the following are happening:

  1. The .attr() sets the HTML attribute for the selected div elements, in this case, the attribute is the class attribute.
  2. The style is attached based on the class defined in the CSS block.
  3. The callback in the style method sets the height and increases it by 10. The unit used here is the pixel.

Here's the output
A simple bar chart

So there you have it. A very simple example that sets you up and running using this awesome data visualization library. I'd be making more posts in the future using D3.


Editor guide