Ricardo Cruz
Ricardo Cruz

Reputation: 3593

D3.js axes not honoring SVG size

I can't seem to be able to place my xaxis and yaxis to the bottom and left of the SVG.

<!DOCTYPE html>
<html>
<head>
<style>
svg {width:350px; height:280px;border-style:solid;}
</style>
</head>

<body>
<svg />

<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var x = d3.scale.linear().domain([0, 80]).range([0, 200]);
var y = d3.scale.linear().domain([0, 80]).range([200, 0]);

var xaxis = d3.svg.axis().scale(x).orient('bottom').ticks(4);
var yaxis = d3.svg.axis().scale(y).orient('left').ticks(4);

var svg = d3.select('svg');
//svg.attr('width', 300).attr('height', 300);
svg.append('g').attr('class', 'xaxis').call(xaxis);
svg.append('g').attr('class', 'yaxis').call(yaxis);
</script>
</body>
</html>

axes not on their proper place

It is as if axes is completely unable to find SVG dimensions.

The only difference I see between my axes instantiation and those of tutorials is that they often create the SVG element on the fly. I would however prefer to manually place the SVG wherever I wish in the HTML...

Upvotes: 0

Views: 274

Answers (1)

Eric Guan
Eric Guan

Reputation: 15982

There's a couple things going on here.

Take a look at my fiddle https://jsfiddle.net/guanzo/e0xp6ae3/

-scale(x).orient('bottom') dictates the position of the axis ticks, and not the location of the axis itself. I fixed this by adding .attr('transform','translate(0,'+280+')') , where 280 is the desired y height of the axis.

-svg hides its overflow by default. In my first fiddle, i hacked together a solution with position: relative and left:20px. It's a horrible solution you see.

The D3 convention is to use margins, like this example https://bl.ocks.org/mbostock/3019563.

By creating the svg element on the fly, we can achieve cleaner, and more flexible code. Check out my updated fiddle that follows the D3 way.

https://jsfiddle.net/guanzo/e0xp6ae3/1/

Basically, the space for the axes is given by the margins. The svg width and height play around the margins. Of course, you can still use hardcoded svg, you just need to change the code around to accommodate.

Upvotes: 2

Related Questions