Skip to content

Instantly share code, notes, and snippets.

@chilijung
Created April 17, 2014 17:29
Show Gist options
  • Save chilijung/10999737 to your computer and use it in GitHub Desktop.
Save chilijung/10999737 to your computer and use it in GitHub Desktop.
Basic bar chart

This is a bar chart in d3.js

name score
howard 60
william 70
jack 100
mike 50
jenny 70
<html>
<head>
<style>
.barchart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
</style>
</head>
<body>
<div class="barchart">
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.5/d3.js"></script>
<script>
var width = 600;
var color = d3.scale.category20();
d3.tsv('./data.tsv', function(data) {
// scale for proper width
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) {return d.score; })])
.range([0, width]);
d3.select('.barchart')
.selectAll('div')
.data(data, function(d) {return d.score})
.enter()
.append('div')
.attr("class", "bar")
.style('width', function(d) { return x(d.score) + 'px';})
.text(function(d) {return d.name})
.style("background-color",function(d,i){return color(i);});
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment