Skip to content

Instantly share code, notes, and snippets.

@ZJONSSON
Created October 22, 2011 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ZJONSSON/1306618 to your computer and use it in GitHub Desktop.
Save ZJONSSON/1306618 to your computer and use it in GitHub Desktop.
D3 - using SVG Bounding Box to get the "automatic padding"
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.0.0"></script>
<style>
path { fill:none;stroke:black}
</style>
<head>.
<body>
<script type="text/javascript">
var w=960,
h=450;
svg=d3.select("body").append("svg:svg").attr("height",h).attr("width",w)
x = d3.scale.linear().range([0, w]).domain([0,100]),
y = d3.scale.linear().range([h, 0])
xAxis = d3.svg.axis().scale(x).tickSize(-h).ticks(5),
yAxis = d3.svg.axis().scale(y).tickSize(-w).orient("left");
var domain=100
// Add the x-axis.
x_svg=svg.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis)
// Add the y-axis.
y_svg=axis = svg.append("svg:g")
.attr("class", "y axis")
// Add y-title - we position it when we change the domain
y_title = svg.append("svg:g")
.append("svg:text")
.text("This is the title of the y-axis")
.style("text-anchor","middle")
// add Chart Title
svg.append("svg:text")
.text("THIS IS THE CHART TITLE")
.attr("x",w/2)
.attr("dy","-1em")
.style("text-anchor","middle")
// add x-title
svg.append("svg:text")
.text("And here is the x-title")
.attr("x",w/2)
.attr("y",h)
.attr("dy","2em")
.style("text-anchor","middle")
function changeDomain() {
domain = (domain==100) ? 999999999 : 100;
y.domain([0,domain])
x.domain([0,domain])
y_svg.call(yAxis)
x_svg.call(xAxis)
// update the location of y_title
y_title.attr("transform","translate("+
(parseFloat(y_svg[0][0].getBBox().x)-10)+" "
+h/2+") rotate(-90)")
//update the viewBox to capture the svg bbox
bbox = svg[0][0].getBBox()
svg.attr("viewBox",bbox.x+" "+bbox.y+" "+bbox.width+" "+bbox.height)
}
changeDomain();
setInterval(changeDomain,1000);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment