Skip to content

Instantly share code, notes, and snippets.

@Wanagram
Last active May 5, 2016 14:07
Show Gist options
  • Save Wanagram/25b5c971f841abdd8ab9e7af2ea653e3 to your computer and use it in GitHub Desktop.
Save Wanagram/25b5c971f841abdd8ab9e7af2ea653e3 to your computer and use it in GitHub Desktop.
final exam question 2

Without modifying the information in genes.json, use D3 to construct a pie chart that shows the relative fraction of genes in the forward and reverse directions. Your code must dynamically generate the pie chart from the data. In other words, if I modify the genes.json data file, the pie chart must update automatically. (15 points)

forked from scresawn's block: final exam question 2

forked from anonymous's block: final exam question 2

[{
"phagename": "D29",
"genes": [{
"name": 1,
"pham": "4858 (107)",
"start": 50,
"stop": 2000,
"direction": "forward"
},
{
"name": 2,
"pham": "a2",
"start": 2150,
"stop": 2900,
"direction": "reverse"
},
{
"name": 3,
"pham": "a3",
"start": 3000,
"stop": 4550,
"direction": "reverse"
},
{
"name": 4,
"pham": "a4",
"start": 4700,
"stop": 7550,
"direction": "reverse"
}],
"genomelength": 15000
}]
<!doctype html>
<html>
<style>
line {
cursor: -webkit-grab;
}
</style>
<body>
<div id="chart"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
d3.json("genes.json", function(error, json) {if (error) return console.warn(error);
var myData = json;
console.log(myData);
//Object that stores gene directions
var directiontally = {forwardtally:0,backtally:0};
//For loop for retrieving/tallying gene direction
for(i=0;i<myData[0].genes.length;i++){
if(myData[0].genes[i].direction == "reverse"){
directiontally.backtally++;
}
else{
directiontally.forwardtally++;
}
}
console.log(directiontally);
var w = 400;
var h = 400;
var r = h/2;
var color = d3.scale.category20c();
var vis = d3.select('#chart').append("svg:svg").data(directiontally).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function(d){return d.backtally;});
// declare an arc generator function
var arc = d3.svg.arc().outerRadius(r);
// select paths, use arc generator to draw
var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i){
return color("black");
})
.attr("d", function (d) {
// log the result of the arc generator to show how cool it is :)
console.log(arc(d));
return arc(d);
});})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment