简体   繁体   English

d3-获取标签的x和y的比例

[英]d3 - get scale of x an y for label

I have created an x and y scale like this: 我创建了一个x和y比例尺,如下所示:

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: 然后,我用它来创建x和y轴,以及如何相对于这些轴定位线:

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. 我还放置标签,以告诉该线的x和y轴在哪里。 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. 这是一个显示问题的jsbin

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. 发生这种情况的原因是,您传递给该函数的对象d是d3.behaviour,它的轴是ax,而y是您拖动到的鼠标位置。 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. 因此,您需要使用invert以便将x,y鼠标坐标分别转换为xScale和yScale的相应x,y值。

The unfortunate thing is that in your object line , you have x, and y and this must have caused the confusion. 不幸的是,在对象line ,您有x和y,这一定引起了混乱。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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