Skip to content

Instantly share code, notes, and snippets.

@anolson
Created May 22, 2012 15:14
Show Gist options
  • Save anolson/2769690 to your computer and use it in GitHub Desktop.
Save anolson/2769690 to your computer and use it in GitHub Desktop.
Super simple bar chart with D3.
<html>
<head>
<title>D3</title>
<link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8" src="d3.v2.js"></script>
<script type="text/javascript" charset="utf-8" src="d3.layout.min.js"></script>
<style type="text/css" media="screen">
body {
margin: 0;
padding: 0;
text-align: center;
font-size: 12px;
font-family: Helvetica
}
#content {
display: inline-block;
}
#chart {
/* margin: 10px;*/
/* border: 1px solid #DDD;*/
}
line { stroke: #777; }
</style>
</head>
<body>
<div id="content">
<div id="chart"></div>
</div>
<script type="text/javascript" charset="utf-8">
var data = [{"x": 1326298868, "value": 20},
{"x": 1326385268, "value": 81},
{"x": 1326471668, "value": 66},
{"x": 1326558068, "value": 33},
{"x": 1326644468, "value": 67},
{"x": 1326730868, "value": 51},
{"x": 1326817268, "value": 87},
{"x": 1326903668, "value": 22}]
var width = 960, height = 500, barWidth = width/data.length;
if(barWidth > 10) {
barWidth = barWidth - 10;
}
var domain = {
x: [d3.min(data, function(d) { return d.x }), d3.max(data, function(d) { return d.x })],
y: [0, d3.max(data, function(d) { return d.value }) + 10]
}
var x = d3.scale.linear().domain(domain.x).range([0, this.width - barWidth]);
var y = d3.scale.linear().domain(domain.y).range([0, this.height]);
var chart = d3.select("#chart").append("svg")
.attr("width", width)
.attr("height", height)
.attr("fill", function(d, i) { return 'steelblue'; })
var plot = chart.append("g")
var xaxis = chart.append("g")
plot.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function(d, i) { return x(d.x) })
.attr("y", function(d) { return height - y(d.value) - 10 })
.attr("width", barWidth)
.attr("height", function(d) { return y(d.value) })
if(barWidth > 20) {
plot.selectAll("text")
.data(data)
.enter().append("text")
.attr("y", 485)
.attr("x", function(d, i) { return x(d.x)})
.attr("dx", barWidth / 2)
.attr("text-anchor", "middle")
.style("fill", "#fff")
.text(function(d) { return d.value; })
}
xaxis.append("line")
.attr("x2", 960).attr("y1", 500).attr("y2", 500)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment