xxxxxxxxxx
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title Here</title>
<script type="text/javascript" src="../d3.v3/d3.v3.js"></script>
</head>
<body>
<script type="text/javascript">
var dataset;
var hist;
var w=700;
var h=505;
d3.csv("nutrition.csv", function(data){
dataset=data;
countOccurences();
frameHisto();
});
var countOccurences=function(){
var histoBlock=[0,0,0,0,0,0,0,0,0,0];
for(var i=0; i<dataset.length; i++){
var fatGram=(parseInt(dataset[i].fat));
if(typeof fatGram==="number"){
if(fatGram<=10){
histoBlock[0]+=1;
}
if(fatGram>10&&fatGram<=20){
histoBlock[1]+=1;
}
if(fatGram>20&&fatGram<=30){
histoBlock[2]+=1;
}
if(fatGram<=40&&fatGram>30){
histoBlock[3]+=1;
}
if(fatGram<=50&&fatGram>40){
histoBlock[4]+=1;
}
if(fatGram<=60&&fatGram>50){
histoBlock[5]+=1;
}
if(fatGram<=70&&fatGram>60){
histoBlock[6]+=1;
}
if(fatGram<=80&&fatGram>70){
histoBlock[7]+=1;
}
if(fatGram<=90&&fatGram>80){
histoBlock[8]+=1;
}
if(fatGram<=100&&fatGram>90){
histoBlock[9]+=1;
}
}
hist=histoBlock;
}
};
var svg = d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h);
var frameHisto=function(){
var newHeight = h-50;
var cVal = d3.scale.category10();
var xScale = d3.scale.ordinal().domain(d3.range(hist.length)).rangeRoundBands([0,w],0.05);
var yScale = d3.scale.linear()
.domain([0,d3.max(hist,function(d){
return d;
})])
.range([0,newHeight]);
svg.selectAll("rect")
.data(hist)
.enter()
.append("rect")
.attr("y",function(d,i){
return h-d-20;
})
.attr("x",function(d,i){
return xScale(i);
})
.attr("height",function(d,i){
return yScale(d);
})
.attr("width",xScale.rangeBand())
.attr("fill",function(d){
return cVal(d);
});
textHisto(xScale,yScale);
};
var textHisto=function(scale,yS){
svg.selectAll("text")
.data(hist)
.enter()
.append("text")
.text(function(d){
return d;
})
.attr("x",function(d,i){
return scale(i)+scale.rangeBand()/3;
})
.attr("y",h);
changeVals(yS,scale);
};
var changeVals=function(yS,xS){
var dataNew = hist;
svg.selectAll("rect")
.on("click",function(){
for(var k=0;k<hist.length;k++){
dataNew[k]=hist[k]*1.5;
}
svg.selectAll("rect")
.data(dataNew)
.transition()
.duration(1000)
.delay(function(d,i){
return i*100;
})
.attr("y",function(d){
return h-d-20;
})
.attr("fill",function(d){
return "rgb("+d*2+",0,0)";
})
.attr("height",function(d){
return yS(d);
});
svg.selectAll("text").data(dataNew).text(function(d){
return d;
})
.attr("x",function(d,i){
return xS(i)+xS.rangeBand()/3;
})
.attr("y",h);
console.log(dataNew);
});
};
</script>
</body>
</html>