d3-graph-gallery.com Open in urlscan Pro
185.199.110.153  Public Scan

URL: https://d3-graph-gallery.com/intro_d3js.html
Submission: On December 16 via manual from SG — Scanned from SG

Form analysis 0 forms found in the DOM

Text Content

← D3.js Graph Gallery Menu
 * 
 * Chart types
 * Quick
   
   Basics
   
   
   Intro to d3 Shape Data wrangling
   
   Customize
   
   
   Axis Color Themes Legend Responsiveness Annotation
   
   Interactivity
   
   
   Tooltip Button Zoom Brushing Transition
   
   React
   
   
   React and d3.js
 * ALL
 * React
 * Related
   Data to viz Dataviz inspiration
   
   Python graph gallery D3.js graph gallery React graph gallery
   
   Who Am I
 * About

✕

X

✕

Submit



AN INTRODUCTION TO D3.JS IN 10 BASIC EXAMPLES.

--------------------------------------------------------------------------------


 * 
 * 
 * 



D3.js is a JavaScript library for manipulating documents based on data. It
allows to build absolutely any type of data visualization. This document
displays 10 interactive examples illustrating the key concepts of d3, leading to
a first basic scatterplot. Note that this online course is a great resource to
get you started with d3.js.

Tech and Gaming


0 of 15 secondsVolume 0%

Press shift question mark to access a list of keyboard shortcuts
Keyboard ShortcutsEnabledDisabled
Play/PauseSPACE
Increase Volume↑
Decrease Volume↓
Seek Forward→
Seek Backward←
Captions On/Offc
Fullscreen/Exit Fullscreenf
Mute/Unmutem
Decrease Caption Size-
Increase Caption Size+ or =
Seek %0-9


facebook twitter Email pinterest
Linkhttps://cdn.jwplayer.com/previews/ht8ISS1h
Copied
Auto180p720p540p360p270p180p

This ad will end in 11
Live
00:03
00:11
00:15







 
 * HTML
 * CSS
 * SVG
 * Javascript and d3.js
 * Console.log()
 * Coordinate system
 * Scale
 * Axis
 * Margin
 * Data binding


WHAT IS HTML?

--------------------------------------------------------------------------------

→ Explanation:

 * HTML stands for Hypertext Markup Language. Basically, it is the language
   behind any website. Web browsers like Mozilla or Safari read this kind of
   file and translate it in a webpage.
 * In a HTML file, elements composing the webpage are created, delineated by
   tags. For instance a title of level 1 is represented by the h1 tag, a
   paragraph with the p tag, an image by the img tag and so on.
 * It is impossible to create a d3.js visualization without basic knowledge on
   html. This tutorial by W3School can be a good starting point in my opinion.


→ Example:


FIRST HTML DOCUMENT

This is my first sentence

This is a link to the d3 graph gallery

← Edit me!

<!DOCTYPE html>

<!-- Add a title -->
<h1>First html document</h1>

<!-- Add a bit of text -->
<p>This is my first sentence</p>

<!-- Add a link -->
<p>This is <a href="https://www.d3-graph-gallery.com">a link to the d3 graph gallery</a></p>





→ Try:
 * Copy and paste the code above in a local file. Call it something like
   test.html. Open it with a browser. You've created your first website!




CUSTOM DOCUMENT STYLE WITH CSS

--------------------------------------------------------------------------------

→ Explanation:

 * CSS stands for Cascading Style Sheet. It allows to apply specific styles to
   the elements created using html before.
 * As for html, it is impossible to create a d3.js visualization without basic
   knowledge on css. If it is new for you, check this tutorial.


→ Example:


FIRST HTML DOCUMENT

This is my first sentence

This is a link to the d3 graph gallery

← Edit me!

<!DOCTYPE html>

<!-- Apply specific style to the elements that have the class `inGreen` -->
<style>
  .inGreen { color: green; }
</style>

<!-- Add a title. Note that the class 'inGreen' is given to this title -->
<h1 class="inGreen">First html document</h1>

<!-- Add a bit of text -->
<p>This is my first sentence</p>

<!-- Add a link -->
<p>This is <a href="https://www.d3-graph-gallery.com">a link to the d3 graph gallery</a></p>




→ Try:
 * Give the class inGreen to one of the paragraph p
 * Create a new class for the first sentence of the document. Change its font
   size with font-size: 20px in css.




BUILD SHAPES WITH SVG

--------------------------------------------------------------------------------

→ Explanation:

 * SVG stands for Scalable Vector Graphic. It is a vector image format.
   Basically, it is a language that allows to build shapes with code.
 * A d3.js chart is actually a set of svg shapes put together. For instant, a
   scatterplot is just composed by several circles as the one shown below.
 * This document of the d3 graph gallery showcases the different shapes offered
   by Svg.


→ Example:


FIRST HTML DOCUMENT

This is my first sentence

← Edit me!

<!DOCTYPE html>
<!-- Add a title -->
<h1>First html document</h1>

<!-- Add a bit of text -->
<p>This is my first sentence</p>

<!-- Add a svg shape -->
<svg>
  <circle style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>




→ Try:

 * Modify the arguments of in the svg call to understand what feature they
   control.
 * Try to draw another type of shape using the cheat sheet below

<line x1="0" y1="0" x2="10" y2="10" stroke="black"></line>
<rect x="0" y="0" width="10" height="10"></rect>
<circle cx="5" cy="5" r="5"></circle>
<ellipse cx="10" cy="5" rx="10" ry="5"></ellipse>
<polygon points="0,0 10,5 20,0 20,20 10,15 0,20"></polygon>
<polyline points="0,0 10,5 20,0 20,20 10,15 0,20" stroke="black"></polyline>
<path d="M65,10 a50,25 0 1,0 50,25"></path>


Example source




MODIFY ELEMENTS WITH JAVASCRIPT AND D3.JS

--------------------------------------------------------------------------------

→ Explanation:

 * JavaScript is one of the three core technologies of the World Wide Web. It
   enables interactivity in webpages.
 * D3.js is a javascript library particularly useful for data visualization. It
   allows to create, select and modify elements.
 * In the example below, d3 is used to select the circle with a class target and
   modify its stroke-width.
 * It is not very impressive yet. But we will use the same kind of process to
   set the position of hundreds of circle and get a scatterplot.


→ Example:


FIRST HTML DOCUMENT

This is my first sentence

 
← Edit me!

<!DOCTYPE html>
<h1>First html document</h1>

<!-- Add a bit of text -->
<p>This is my first sentence</p>

<!-- Add a svg shape. Note that the 'target' class is attributed to the circle -->
<svg> 
  <circle class="target" style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>
d3
  .select(".target")  // select the elements that have the class 'target'
  .style("stroke-width", 8) // change their style: stroke width is not equal to 8 pixels
</script>

→ Try:

 * Change the circle opacity with the opacity style that goes between 0 and 1.



CONSOLE.LOG() IS YOUR FRIEND.

--------------------------------------------------------------------------------

→ Explanation:

 * So the browser runs Html, Css and Javascript code and shows the result as a
   webpage.
 * If there is something wrong, it will give notification in the console.
 * Usually you can open the console with right click -> inspect element
 * You can output stuff in the console using the console.log("sometext") in your
   javascript code
 * This is obvious for people coming from web development. But isn't for people
   coming from other field (R?). It is essential to be able to debug your code.


THE COORDINATE SYSTEM

--------------------------------------------------------------------------------

→ Explanation:

 * Building a d3.js chart starts by creating a svg element. This element has a
   width and a height, given in pixels.
 * It is important to understand that the top left corner has the coordinate x=0
   and y=0. The bottom left corner has the coordinate x=0 and y=height. The top
   right corner has the coordinate x=width and height=0


→ Example:

← Edit me!

<!DOCTYPE html>

<!-- Add a svg area, empty -->
<svg id="dataviz_area" height=200 width=450></svg>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>
var svg = d3.select("#dataviz_area")
svg.append("circle")
  .attr("cx", 2).attr("cy", 2).attr("r", 40).style("fill", "blue");
svg.append("circle")
  .attr("cx", 140).attr("cy", 70).attr("r", 40).style("fill", "red");
svg.append("circle")
  .attr("cx", 300).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>

→ Try:

 * Change the coordinate of the 3 circles to make sure you understood how it
   works



FROM DATA TO PIXEL: SCALES

--------------------------------------------------------------------------------

→ Explanation:

 * Position of element is set in pixel. But input dataset is not.
 * We thus need a function that translate a numeric variable to a position in
   pixel. It is called a scale
 * If my data are percentages and my svg area is 400px width. 0% → 0px. 100% →
   400px. 50% → 200px.
 * Scale always have a domain (0 to 100% here) and a range (0 to 400px here)
 * Usually the scale for the X axis is called x. If you run x(10), d3 returns
   the position in px for this value


→ Example:
← Edit me!

<!DOCTYPE html>

<!-- Add a svg area, empty -->
<svg id="viz_area" height=200 width=450></svg>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>
// Select the svg area
var svg = d3.select("#viz_area")

// Create a scale: transform value in pixel
var x = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([0, 400]);       // This is the corresponding value I want in Pixel
// Try console.log( x(25) ) to see what this x function does.

// Add 3 dots for 0, 50 and 100%
svg.append("circle")
  .attr("cx", x(10)).attr("cy", 100).attr("r", 40).style("fill", "blue");
svg.append("circle")
  .attr("cx", x(50)).attr("cy", 100).attr("r", 40).style("fill", "red");
svg.append("circle")
  .attr("cx", x(100)).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>

→ Try:

 * Change domain and range values to understand how it works.
 * Add a Y scale to move the circles up or down. Remember 0px is on top!



ADD AXIS

--------------------------------------------------------------------------------

→ Explanation:
 * D3 offers a few function to draw axis automatically.
 * These axis are always drawn on top of a scale. This scale specifies where the
   axis must be placed, and what range it should indicate.
 * The function axisBottom() creates a horizontal axis, with ticks and labels at
   the bottom. axisLeft() will be used later for the Y axis


→ Example:
0102030405060708090100
← Edit me!

<!DOCTYPE html>

<!-- Add a svg area, empty -->
<svg id="Viz_area" height=200 width=450></svg>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>
// Select the svg area
var svg = d3.select("#Viz_area")

// Create a scale: transform value in pixel
var x = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([0, 400]);       // This is the corresponding value I want in Pixel

// Show the axis that corresponds to this scale
svg.call(d3.axisBottom(x));

// Add 3 dots for 0, 50 and 100%
svg.append("circle")
  .attr("cx", x(10)).attr("cy", 100).attr("r", 40).style("fill", "blue");
svg.append("circle")
  .attr("cx", x(50)).attr("cy", 100).attr("r", 40).style("fill", "red");
svg.append("circle")
  .attr("cx", x(100)).attr("cy", 100).attr("r", 40).style("fill", "green");
</script>

→ Try:

 * Change domain and range values to understand how it works.



MARGIN & TRANSLATION

--------------------------------------------------------------------------------

→ Explanation:
 * The axis position often needs to be adjusted. For instance, the X axis is
   usually placed at the bottom of the chart.
 * This is made possible thanks to translation. Basically, applying
   .attr("transform", "translate(20,50)") to an element with translate it 20px
   to the right and 50px to the bottom.
 * A very common strategy is to apply a translation to the general svg area,
   creating a bit of margin around the chart without having to think about it in
   the rest of the code. It is important to understand how it works since almost
   all d3.js chart start that way.


→ Example:
01020304050607080901000102030405060708090100
← Edit me!

<!DOCTYPE html>

<!-- Add a svg area, empty -->
<div id="Area"></div>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 40, bottom: 30, left: 30},
    width = 450 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var sVg = d3.select("#Area")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  // translate this svg element to leave some margin.
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// X scale and Axis
var x = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([0, width]);       // This is the corresponding value I want in Pixel
sVg
  .append('g')
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// X scale and Axis
var y = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([height, 0]);       // This is the corresponding value I want in Pixel
sVg
  .append('g')
  .call(d3.axisLeft(y));

</script>

→ Try:
 * Play with the margin values to double check how it works.
 * Remove some lines in the svg variable creation.



DATA BINDING

--------------------------------------------------------------------------------

→ Explanation:
 * Binding data to svg elements is the last step we need to complete the
   scatterplot. It is also the hardest part to understand in my opinion.
 * It always follows the same steps:
    * svg: this select the svg area where the chart takes place
    * .selectAll("whatever"): select all the elements that have not be created
      yet, I know it is weird.
    * .data(data): specify the data to use.
    * .enter(): start a loop for the data. Following code will be applied to
      data[0], data[1] and so on.
    * .append("circle"): for each iteration, add a circle.
    * .attr("cx", function(d){ return x(d.x) }): gives the x position of the
      circle. Here d will be data[0], then data[1] and so on. Thus d.x is the
      value of x, and x(d.x) is the corresponding position in pixel found thanks
      to the x scale.


→ Example:
01020304050607080901000102030405060708090100
← Edit me!

<!DOCTYPE html>

<!-- Add a svg area, empty -->
<div id="scatter_area"></div>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>



<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 40, bottom: 30, left: 30},
    width = 450 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svG = d3.select("#scatter_area")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Create data
var data = [ {x:10, y:20}, {x:40, y:90}, {x:80, y:50} ]

// X scale and Axis
var x = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([0, width]);       // This is the corresponding value I want in Pixel
svG
  .append('g')
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// X scale and Axis
var y = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([height, 0]);       // This is the corresponding value I want in Pixel
svG
  .append('g')
  .call(d3.axisLeft(y));

// Add 3 dots for 0, 50 and 100%
svG
  .selectAll("whatever")
  .data(data)
  .enter()
  .append("circle")
    .attr("cx", function(d){ return x(d.x) })
    .attr("cy", function(d){ return y(d.y) })
    .attr("r", 7)


</script>

→ Note:

This is probably the most difficult concept in d3.js. And it is used in almost
every single chart. It is actually the power of d3: binding data to elements

It is probably a good idea to read more on this topic. Check d3 in depth and
Dashing d3.js.



WHAT'S NEXT?

--------------------------------------------------------------------------------

This document is a very very short intro to d3.js. However, it describes the
basic concepts that are used in almost every chart.

You're now probably ready to explore the gallery. For each chart section, there
is a very basic example to start with.







CONTACT

This document is a work by Yan Holtz. Any feedback is highly encouraged. You can
fill an issue on Github, drop me a message on Twitter, or send an email pasting
yan.holtz.data with gmail.com.

Github Twitter
Copyright © the d3 graph gallery 2018
 * 
 * 
 * 

 * Privacy Policy
 * Terms of Use

✕
Do not sell or share my personal information.
You have chosen to opt-out of the sale or sharing of your information from this
site and any of its affiliates. To opt back in please click the "Customize my ad
experience" link.

This site collects information through the use of cookies and other tracking
tools. Cookies and these tools do not contain any information that personally
identifies a user, but personal information that would be stored about you may
be linked to the information stored in and obtained from them. This information
would be used and shared for Analytics, Ad Serving, Interest Based Advertising,
among other purposes.

For more information please visit this site's Privacy Policy.
CANCEL
CONTINUE


Information from your device can be used to personalize your ad experience.

Do not sell or share my personal information.
A Raptive Partner Site