D3.js selectors d3.select

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>

JavaScript

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

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

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