Learn D3 step by Step
It’s always good to read and follow the instruction manual first when you’re learning new language or tool set. Also you can google for good tutorials and more.
D3 (Data-Driven Documents) is a JS library that helps you to visualize your data using HTML, SVG and CSS.
First step include D3 library into your HTML file
#main selector
d3.select(“selector”) or d3.selectAll(“selector”)
define a selector element
var body = d3.select(“body”)
Now you can use
body.select(“selector”) or body.selectAll(“selector”)
Also you can use append() function like
Set this in new variable
var h1 = body.select(“h1”)
Now we can apply different attributes by using attr()
Alternatively
Also we can apply style method same as attrribute method
classed() function and usage
h1.classed(“className”, true) will add a className into h1 selector without deleting previews className.
if you apply h1.attr(“class”, “className”) it will replace the previews class
h1.classed(“className”, false) will remove a className from h1 selector
Also we can use html() method
h1.html(“ Hello from D3”);
append() applies after the element. So if we want to insert something before the element?
We can use insert() for insert element before the selected element.
Inserting <p> element before <h1> element.
And we can use remove() method
#SVG Introduction
SVG stands for Scalable Vector Graphic basically graphical version of HTML. We can create basic svg by using
This are the basic SVG elements and you can create more advanced SVGs.
Let’s back to the D3 and how we can select SVG element on D3
Due to select a SVG element, we need to define svg first
Now you can select the element and append the value
#Start using a Basic Data
Make sure we have created the HTML first and include D3 & the data file as well
Basic data file
The code below that represents how to create basic rectangle graph
#Lets start using scales
Scales gives you more flexible injection into the graph elemnts that you’re working on.
d3.scale.linear uses the Linear Algebra method like y = mx + b.
On the example we know that min value 0 and max value 100.
Ex: If we set a(5) then the return will be (“0.5px”). In here the scale function does the math and it return the string value.
In the is example scale function return color schema between red and green.
Let’s see if we can create a graphic that fits in your window screen using scale function and it’s range.