Create a gist now

Instantly share code, notes, and snippets.

Colour Density Grid

Colour Density Grid

Dots are placed randomly, then they are grouped by the grid. The tile colour is determined by the dot density. Raster is a grid.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Colour Density Grid</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<div id="chartArea"></div>
<script src="js.js"></script>
</body>
</html>
var height = 500;
var width = 900;
var data = [];
var grid_spacing = 100;
var max_cell_density = 0;
for(var i = 0; i < 75; i++){
data.push([Math.random()*width, Math.random()*height]);
}
var matrix = [];
for(var i=0; i<width/grid_spacing; i++) {
matrix[i] = new Array(Math.floor(height/grid_spacing));
}
//Matrix population
data.forEach(function(d) {
x = parseInt(d[0]/grid_spacing)
y = parseInt(d[1]/grid_spacing)
matrix[x][y] = isNaN(matrix[x][y]) ? 1 : matrix[x][y] + 1
if(matrix[x][y] > max_cell_density)
max_cell_density = matrix[x][y]
})
var svg = d3.select("#chartArea")
.append("svg")
.attr("width", width)
.attr("height", height);
var color = d3.scale.linear()
.domain([0, max_cell_density/2])
.range(['white', '#8ca252'])
.interpolate(d3.interpolateLab);
//Applying colouring to each cell
matrix.forEach(function(col, col_num){
col.forEach(function(cell, row_num){
svg.append('rect')
.style('fill', color(cell))
.style('opacity', .7)
.attr('x', col_num*grid_spacing)
.attr('y', row_num*grid_spacing)
.attr('width', grid_spacing)
.attr('height', grid_spacing)
})
})
var circles = svg.selectAll('circle')
.data(data).enter()
.append('circle')
.style('fill', 'maroon')
.style('stroke', 'orange')
.attr('cx', function(d) { return d[0]; })
.attr('cy', function(d) { return d[1]; })
.attr('r', 4)
//Drawing grid
for(var wi = 0; wi <= width; wi+=grid_spacing){
svg.append('line')
.style('stroke', 'black')
.attr('x1', wi)
.attr('x2', wi)
.attr('y1', 0)
.attr('y2', height)
}
for(var hi = 0; hi <= height; hi+=grid_spacing){
svg.append('line')
.style('stroke', 'black')
.attr('x1', 0)
.attr('x2', width)
.attr('y1', hi)
.attr('y2', hi)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment