I\'m using some code from d3.js to build a cell sheet in an html page dynamically. So if it is a 5x5 .csv report, it will produce 5x5 on the page and so forth.
This repo
I suggest you use a threshold scale, which:
are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. The input domain is still continuous, and divided into slices based on a set of threshold values. The input domain is typically a dimension of the data that you want to visualize, such as the height of students (measured in meters) in a sample population. The output range is typically a dimension of the desired output visualization, such as a set of colors (represented as strings).
So, if you do:
var colorScale = d3.scale.threshold()
.domain([30, 70])
.range(["red", "yellow", "green"]);
You'll create a scale that will return "red" if the value is less than 30, "yellow" if the value is between 30 and 70, and finally "green" for over 70.
Then, you do:
.style("background-color", function(d){
return colorScale(d);
})
Check this demo (I'm using my own table code, a little bit different from yours, but the principle is the same):
var parsedCSV = d3.csv.parse(d3.select("#csv").text());
var colorScale = d3.scale.threshold()
.domain([30, 70])
.range(["red", "yellow", "green"]);
var body = d3.select("body");
var headers = Object.keys(parsedCSV[0]);
var table = body.append('table')
var thead = table.append('thead')
var tbody = table.append('tbody');
var head = thead.selectAll('th')
.data(headers)
.enter()
.append('th')
.text(function(d) {
return d;
});
var rows = tbody.selectAll('tr')
.data(parsedCSV)
.enter()
.append('tr');
var cells = rows.selectAll('td')
.data(function(d) {
return Object.values(d);
})
.enter()
.append('td')
.style("background-color", function(d) {
return colorScale(d);
})
.text(function(d) {
return d;
});
pre {
display: none;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td,th {
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<pre id="csv">foo,bar,baz
32,55,67
12,34,99
11,21,32
11,65,76
99,14,23</pre>
You should be able to just append a .style after your last .text(). It will be something along the lines of:
.append('td')
.text(...)
.style('background-color', function(d) {
if (d < 3) {return 'green';}
else if (d < 5) {return 'yellow';}
else if (d < 10) {return 'orange';}
else {return 'red';}
};
Might take a bit of fiddling around with the return values for the colours, not sure whether returning strings will work, might be better to return rgb(...) colours instead.