I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value?
Here is what I currently have:
//Create an SVG Container
var svgContainer = d3.select("body").selectAll("svg")
.data(data)
.enter().append("svg")
.attr("width", 38)
.attr("height", 25);
//Draw the rectangle
var rectangle = svgContainer.append("rect")
.attr("x", 5)
.attr("y", 5)
.attr("width", 38)
.attr("height", 25)
//Adjusting color here based on data points; aiming for different shades of red based on data values
.style("fill", function(d) {
return "rgb(255," + (d.Two * 2) + ",0)";
});
Assuming my data appears as follows:
var data = [{One:420, Two:222, Three:332},...]; And I desire only the "Two" values to influence the color of the rectangles