Search code examples
javascriptd3.jssvgscalingaxes

Scaling Axis with D3 JavaScript


I have plotted the X and Y axes. I have couple of points to show on the axis. My points vary for X axis from 4.5 to 8 and for Y axis from 2 to 4.

You can find the DEMO of what I have done.

function kmeans(){
    x_means[0] = 5.9;

    plotMeans();
}

The problem is this chart shows the points such as 0.59. However, I can't see when I give the value of 5.9 since it falls out of the chart.

Any ideas on how to solve this?

Thank you!


Solution

  • If you inspect your javascript console, you'll see this error:

    Error: Invalid value for <circle> attribute cy="NaN"
    

    This is because the data you feed d3 is:

    > numeric.transpose([[0.59],[]])
        Array[2]
          0: 0.59
          1: undefined
    

    So that:

    .attr("cy", function(d, i){return Y(d[1]);});
    

    is an operation on undefined.

    EDITS

    Do'h, just re-read your question. Your scales need a domain, this is the user space span of your coordinate space. The range then is is the pixel span of your coordinate space. The scale maps the two together:

    var X = d3.scale.linear()
        .range([0, width]) //<-- 0 to 960 pixels
        .domain([0,10]); //<-- maps to coordinates 0 to 10
    

    See update here.

    I also modified it to use proper axis so it's easier to visualize.