I got a problem with using an csv-file in d3.js.
At first, I got my visualization by using an array with data:
var dataset = [1,1,1,1,1,1,1,2,3,4]
Depending on the number, there will be a different color for a rectangle. I did this by using the following lines of code:
.style("fill", function(d) {
if (d==1) {return "black"}
else if (d==2) {return "red"}
else if (d==3) {return "yellow"}
else if (d==4) {return "green"}
else {return "purple"}
;})
Because I want to make my code more flexible, I want to do the same using an csv-datafile. It looks like this:
2008
1
1
1
1
2
3
4
I included it with the following line of code:
d3.csv("landtag.csv", function(d) {
}
But, it doesn't work: All rectangle are purple, therefore the "else" was chosen.
The number of circles depends on the datalength - this is working!
Why is that possible? Do I insert the csv-file in the wrong way?
I tried already some solutions in tutorials, but none worked.
Thanks for your help!
My complete code:
// Width and height
var w = 1000;
var h = 1000;
// create svg variable
var svg = d3.select("p")
.append("svg")
.attr("id", "sitze") ;
var sitze;
d3.csv("landtag.csv", function(d) {
// create variable
var rect = svg.selectAll("rect")
.data(d["2008"])
.enter()
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 50)
.attr("height", 50)
//Bar width depending on number of datapoints in array
.attr("x", function(d, i) {
return i * (w / d.length);
})
// if for different colors
.style("fill", function(d) {
if (d=="1") {return "black"}
else if (d=="2") {return "red"}
else if (d=="3") {return "yellow"}
else if (d=="4") {return "green"}
else {return "purple"}
;})
// paddings
.attr("x", function(d, i) {return (i % 17) * 55;})
.attr("y", function(d, i) {return Math.floor(i / 17) * 55;});
})