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

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

问题描述

我用 D3 显示一个折线图,代码大致如下(给定比例函数 xy 和浮点数组 data):

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));

现在我想知道线在给定水平像素位置的垂直高度.data 数组的数据点比像素少,并且显示的线是内插的,因此仅从给定像素处推断线的高度并不直接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.

有什么提示吗?

推荐答案

2012 年 9 月 19 日根据评论编辑 非常感谢 nrabinowitz!

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

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")));

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

For me this returns [5.000403881072998, 140.6229248046875].

这个搜索函数 findYatX 远非有效(在 O(n) 时间内运行),但说明了这一点.

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

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

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