Skip to content

Instantly share code, notes, and snippets.

@nfisher
Created June 24, 2013 23:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nfisher/5854585 to your computer and use it in GitHub Desktop.
Save nfisher/5854585 to your computer and use it in GitHub Desktop.
Simple D3.js SVG heatmap
<!doctype HTML>
<title>D3 Test</title>
<script src="d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
body {
margin:0 auto;
position:relative;
width:958px;
}
.chart rect {
stroke: white;
}
</style>
<body>
</body>
<script>
function cell_dim(total, cells) { return Math.floor(total/cells) }
var total_height = 300;
var total_width = 900;
var rows = 12; // 1hr split into 5min blocks
var cols = 24; // 24hrs in a day
var row_height = cell_dim(total_height, rows);
var col_width = cell_dim(total_width, cols);
var data = [];
for (var i = 0; i < (rows * cols); i++) {
data[i] = Math.random();
console.log(i);
}
var color_chart = d3.select("body")
.append("svg")
.attr("class", "chart")
.attr("width", col_width * cols)
.attr("height", row_height * rows);
var color = d3.scale.linear()
.domain([d3.min(data), 1])
.range(["#8b0000", "#FFF0F0"]);
color_chart.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d,i) { return Math.floor(i / rows) * col_width; })
.attr("y", function(d,i) { return i % rows * row_height; })
.attr("width", col_width)
.attr("height", row_height)
.attr("fill", color);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment