简体   繁体   中英

Moving the axes in d3.js

I have two axes in my graph right now, that are stuck at the very left and bottom of the graph. I want to make the axes line up with the (0,0) coordinate, or in other words I want the axes to be at x=0 and y=0

Here's my axes code:

    //setup x
var xAxis = d3.svg.axis()
    .scale(xRange)
    .tickSize(5)
    .tickSubdivide(true),

    //setup y
    yAxis = d3.svg.axis()
    .scale(yRange)
    .tickSize(5)
    .orient("left")
    .tickSubdivide(true);

I was thinking that the way to do it might just be to make a smaller svg underneath the one that I have, that starts at zero, and put the axes there, and remove them from the one I have right now.

Here's the full code: http://jsfiddle.net/v92q26L8/

The key part of your code is the bit where you attach the axes

vis.append("svg:g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(xAxis);

vis.append("svg:g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(yAxis);

At the moment you are positioning the axes bottom and left using transforms on the groups ( svg:g nodes) which contain them.

To reposition the axes you simply need to adjust these transforms using your defined scales.

For your x axis

.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")

becomes

.attr("transform", "translate(0," + yRange(0) + ")")

for your y axis

.attr("transform", "translate(" + (MARGINS.left) + ",0)")

becomes

.attr("transform", "translate(" + xRange(0) + ",0)")

Additionally, it may be sensible to change the names of your scales. The term 'range' has a very particular meaning in D3, I'd suggest xScale and yScale.

JS Fiddle

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