在d3中,如何从SVG行获取插入线数据? [英] In d3, how to get the interpolated line data from a SVG line?

查看:226
本文介绍了在d3中,如何从SVG行获取插入线数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用D3大致显示一个折线图(给定比例函数 x y 浮点数组 data ):

  var line = d3.svg。 line()
.interpolate(basis)
.x(function(d,i){return x(i);})
.y (d);});
d3.select('。line')。attr('d',line(data));

现在,我想知道给定水平像素位置的线的垂直高度。 data 数组比像素的数据点少,显示的行是 interpolated ,因此不直接推导出行的高度



任何提示?



您需要对由 getPointAtLength 返回的数据进行某种搜索。 (请参阅 https://developer.mozilla.org/en-US/docs/ DOM / SVGPathElement 。)

  // Line 
var line = d3.svg.line
.interpolate(basis)
.x(function(d){return i;})
.y(function(d,i){return 100 * Math.sin(i )+ 100;});

//追加DOM的路径
d3.select(svg#chart)//或任何你的SVG容器是
.append(svg:path )
.attr(d,line([0,10,20,30,40,50,60,70,80,90,100]))
.attr(id,myline );

//获取坐标
function findYatX(x,linePath){
function getXY(len){
var point = linePath.getPointAtLength(len);
return [point.x,point.y];
}
var curlen = 0;
while(getXY(curlen)[0]< x){curlen + = 0.01; }
return getXY(curlen);
}

console.log(findYatX(5,document.getElementById(myline)));

对我来说,这会返回[5.000403881072998,140.6229248046875]。



这个搜索函数 findYatX 远不是有效的(在 O(n)时间运行) / p>

I display a line chart with D3 with roughly the following code (given the scale functions x, y and the float array data):

 var line = d3.svg.line()
         .interpolate("basis")
         .x(function (d, i) { return x(i); })
         .y(function (d) { return y(d); });
 d3.select('.line').attr('d', line(data));

Now I want to know the vertical height of the line at a given horizontal pixel position. The data array has lesser data points than pixels and the displayed line is interpolated, so it is not straight-forward to deduce the height of the line at a given pixel just from the data array.

Any hints?

解决方案

Edited 19-Sep-2012 per comments with many thanks to nrabinowitz!

You will need to do some sort of search of the data returned by getPointAtLength. (See https://developer.mozilla.org/en-US/docs/DOM/SVGPathElement.)

// Line
var line = d3.svg.line()
     .interpolate("basis")
     .x(function (d) { return i; })
     .y(function(d, i) { return 100*Math.sin(i) + 100; });

// Append the path to the DOM
d3.select("svg#chart") //or whatever your SVG container is
     .append("svg:path")
     .attr("d", line([0,10,20,30,40,50,60,70,80,90,100]))
     .attr("id", "myline");

// Get the coordinates
function findYatX(x, linePath) {
     function getXY(len) {
          var point = linePath.getPointAtLength(len);
          return [point.x, point.y];
     }
     var curlen = 0;
     while (getXY(curlen)[0] < x) { curlen += 0.01; }
     return getXY(curlen);
}

console.log(findYatX(5, document.getElementById("myline")));

For me this returns [5.000403881072998, 140.6229248046875].

This search function, findYatX, is far from efficient (runs in O(n) time), but illustrates the point.

这篇关于在d3中,如何从SVG行获取插入线数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆