Skip to content

Instantly share code, notes, and snippets.

@AgalyaLoganathan
Created October 10, 2012 12:22
Show Gist options
  • Save AgalyaLoganathan/3865263 to your computer and use it in GitHub Desktop.
Save AgalyaLoganathan/3865263 to your computer and use it in GitHub Desktop.
d3 segment chart
<!doctype html>
<html>
<head>
<title>Segment Graph</title>
<style>
#segmentChart {
width: 400px;
height: 100px;
}
</style>
<script src="https://raw.github.com/mbostock/d3/master/d3.v2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="http://underscorejs.org/underscore-min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var data=[{key: 2011, values : [10,100]},{key: 2012, values: [20, 150]}, {key: 2013, values: [30, 120]}];
var d3Data = []
var lowDomain=0, highDomain=0;
_.each(data, function(obj,index) {
if(-obj.values[0]<lowDomain) { lowDomain = -obj.values[0]; }
if(obj.values[1]>highDomain) { highDomain=obj.values[1]; }
obj.values[0] = -obj.values[0];
});
var chartWidth = $("#segmentChart").width();
var margin = 10;
var colors = d3.scale.category10();
x = d3.scale.linear().domain([lowDomain,highDomain]).range([margin,chartWidth-margin]);
var availableHeight = $("#segmentChart").height()-margin*2;
barHeight = availableHeight / (data.length + (data.length-1)/2);
var chart = d3.select("#segmentChart").selectAll(".series")
.data(data)
.enter()
.append("g").classed("series",true).style("fill",function(d,i) { return colors(i) })
.attr("transform",function(d,i) { return "translate(0,"+(margin+i*barHeight*1.5)+")"; })
.selectAll("rect").data(function(d,i){ console.log(d);return d.values;})
.enter()
.append("rect")
.attr("x",function(d,i) { if(d<0) { return x(d); } else { return x(0); } })
.attr("y",0)
.attr("width",function(d,i) { return Math.abs(x(d)-x(0)); })
.attr("height", barHeight)
.append("title").text(function(d,i) { return Math.abs(d); });
d3.select("#segmentChart").append("line").attr("x1",x(0)).attr("y1",margin).attr("x2",x(0)).attr("y2",margin+availableHeight).attr("style","stroke:black")
});
</script>
</head>
<body>
<svg id="segmentChart">
</svg>
</body>
</html>
@biovisualize
Copy link

Could you please fix the broken link to d3.js, using http://d3js.org/d3.v2.min.js ? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment