简体   繁体   中英

d3 - get scale of x an y for label

I have created an x and y scale like this:

var xScale = d3.scale.linear()
    .domain([0, 20])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, 20])
    .range([height, 0]);

I then use this to create an x and y axis as well as how to position a line with respect to these axis:

var line = {
    start: {x: 2, y: 3, type: 'start'},
    finish: {x: 14, y: 6, type: 'finish'} 
  };

var g = svg.append('g');

  g.append('line')
      .style('stroke', 'blue')
      .attr('class', 'line')
      .attr('x1', xScale(line.start.x))
      .attr('y1', yScale(line.start.y))
      .attr('x2', xScale(line.finish.x))
      .attr('y2', yScale(line.finish.y));

I also position labels that tell where the x and y axis of the line are. The end points of the line are draggable but I can't get the scaled coordinates in the drag event:

var drag = d3.behavior
     .drag()
     .on("drag", function(d) {
        var circle = d3.select(this),
            line = d3.select('.line'),
            isStart = circle.classed('start'),
            textClass = isStart ? ".textstart" : ".textfinish",
            lineX = isStart ? 'x1' : 'x2',
            lineY = isStart ? 'y1' : 'y2',
            text = d3.select(textClass);

        text.text( function (d) { return "( " + d.x  + ", " + d.y +" )"; });

        line.attr(lineX, d3.event.x).attr(lineY, d3.event.y);
        text.attr('x', d3.event.x).attr('y', d3.event.y - 20);
        circle.attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
     });  

Here is a jsbin that shows the problem.

May I suggest you change the line:

text.text( function (d) { return "( " + d.x  + ", " + d.y +" )"; });

to:

text.text( function (d) { return "( " + d3.format(",.2f")(xScale.invert(d.x))  + ", " + d3.format(",.2f")(yScale.invert(d.y)) +" )"; });

That way you will display the value you want as in the following image:

在此处输入图片说明

The reason this happens is because the object d you are passing to the function, is the d3.behaviour which has as ax, and y, the mouse locations of where you dragged to. Thus you need to use invert so as to convert the x,y mouse coordinates, to their corresponding x,y values of the xScale, and yScale respectively.

The unfortunate thing is that in your object line , you have x, and y and this must have caused the confusion.

I hope this helps.

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