Skip to content

Instantly share code, notes, and snippets.

@martinjc
Last active May 14, 2021 16:58
Show Gist options
  • Save martinjc/39f4c5da66a7a65ee34f7a5f44c47774 to your computer and use it in GitHub Desktop.
Save martinjc/39f4c5da66a7a65ee34f7a5f44c47774 to your computer and use it in GitHub Desktop.
Simple bar chart (Data: randomly generated)
license: mit
border: no

Simple example using D3 to create a bar chart of some randomly generated data

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 example</title>
<script src="//d3js.org/d3.v4.min.js" charset="utf-8"></script>
<style>
.bar {
fill: red;
}
</style>
</head>
<body>
<input type="button" onclick="update()" value="Update"/>
<div id="vis">
</div>
<script src="script.js"></script>
</body>
</html>
function createRandomData() {
var numDataItems = Math.floor((Math.random() * 10) + 1);
var d = [];
for(var i = 0; i < numDataItems; i++) {
d.push(Math.floor((Math.random() * 50) + 1));
}
return d;
}
var width = 500;
var height = 500;
var svg = d3.select('#vis')
.append('svg')
.attr('width', width)
.attr('height', height);
function update() {
var exampleData = createRandomData();
console.log(exampleData);
var bars = svg.selectAll('.bar')
.data(exampleData);
bars
.exit()
.remove()
var new_bars = bars
.enter()
.append('rect')
.attr('class', 'bar')
.attr('height', '20px')
.attr('x', 0);
new_bars.merge(bars)
.attr('width', function(d){ return d*10 + 'px'; })
.attr('y', function(d, i){ return (i * 20) + i; });
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment