D3.js tutorial examples

by Imabot

HTML

<script src="https://d3js.org/d3.v5.min.js"></script>
<h1>My first bar chart with D3.js</h1>

<div id="bar-chart"></div>

CSS

#bar-chart { width:100%; background-color:grey; }
#bar-chart svg { background-color: Gainsboro; }
#bar-chart .bars { fill: LightSkyBlue; }

JavaScript

// Set of data
var dataset = [31, 64, 42, 28, 16, 32, 64, 90];

// Get parent size
var width = d3.select('#bar-chart').node().getBoundingClientRect().width;
var height = width/2;

// Create our SVG container with grey background
var svg = d3.select("#bar-chart")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

// Create a group for the bars
var bars = svg.append('g')
			.attr('class', 'bars');


// Bind data to chart, and create bars
bars.selectAll('rect')
	.data(dataset)
    .enter()    
    .append('rect')
    .attr('x', (d,i) => i*25 )
    .attr('y', (d) => 100-d)
    .attr('width', 20)
    .attr('height', (d) => d);