whytheq whytheq - 1 month ago 9
Javascript Question

Linking 3 simple squares to data which includes required color

I have the following - what I'm trying to achieve is 3 squares with each square joined to a different member in the simple data structure

dta
. How do I link the color of each square to the string
colr
in
dta
?

//############# SQUARES ###################
function dsSquares() {

var dta = {
categ: ["N", "P", "B"],
colr: ["yellow", "pink", "blue"]
}

var basics = dsSquaresBasics();
var margin = basics.margin,
width = basics.width,
height = basics.height;

//Create SVG element
var SQsvg = d3.select("#threeSquares")
.append("svg:svg")
//.data(dta)
.attr({
"width": width + margin.left + margin.right,
"height": height + margin.top + margin.bottom,
id: "squaresArea"
});

var SQg = SQsvg
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
SQg.selectAll("rect")
.data(dta.categ)
.enter()
.append("rect")
.attr({
x: margin.left,
y: function(d, i) {
return i * 65
},
"width": width,
"height": 50,
//fill: 'green' //<<<<<WORKS OK
fill: dta.colr //<<<<<NOT WORKING
})
.on("click", up);


function up(d, i) {
//update bar chart when user selects a square
updateBarChart(d, "green");
console.log(d);
}

}

dsSquares();


The above is part of my first D3 attempted visual, saved here:

https://plnkr.co/edit/Y5plUy?p=preview

Please note: I realize that the function
updateBarChart()
in the above is not yet fully working but that is the next block in the jigsaw so I have no need for help with that ...yet!

Answer

The data in dta.colr is not bound to the rectangles. A better approach would be defining the color together with categ, in an array of objects.

If changing your data structure is not an option, you can color the rectangles based on their indices:

fill: function(d,i){ return dat.colr[i];}
Comments