简体   繁体   中英

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>

轴不在正确的位置

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM