2015-12-16 79 views
1

我正在使用d3js绘制多线图。使用通用函数绘制线d3js

我的划线功能如下。

meanLine = d3.svg.line() 
      .interpolate('linear') 
      .x(function (d) { 
       return xScale(d.date); 
      }) 
      .y(function (d) { 
       return yScale(d.mean); 
      }); 

//data is declared at top 
group.append('svg:path') 
      .attr({ 
       d: meanLine(data), 
       "stroke": "rgba(" + color + ", 0.8)", 
      }); 

这里的日期和平均值是硬编码的。我想要一个通用函数,我可以通过哪个值来绘制线条。

我想是这样

lineFunc = d3.svg.line() 
      .interpolate('linear') 
      .x(function (d, xval) { 
       return xScale(d[xval]); 
      }) 
      .y(function (d, yval) { 
       return yScale(d[yval]); 
      }); 

//data is declared at top 
group.append('svg:path') 
      .attr({ 
       d: lineFunc(data, xval, yval), 
       "stroke": "rgba(" + color + ", 0.8)", 
      }); 

回答

1

你可以做这样的事情......这里myLineFun房子你d3 line function

//make a function which houses the line function 
var myLineFun = function(data, xval, yval){ 
     //the line function 
     var lineFunc = d3.svg.line() 
      .interpolate('linear') 
      .x(function (d) { 
       return xScale(d[xval]);//xval passed in the argument 
      }) 
      .y(function (d) { 
       return yScale(d[yval]);//yval passed in the argument 
      }); 
     return lineFunc(data);//this will return the d attribute 
} 

然后再调用这个:

group.append('svg:path') 
      .attr({ 
       d: myLineFun(data, xval, yval), 
       "stroke": "rgba(" + color + ", 0.8)", 
      }); 

希望这有助于!

+1

我做了一个编辑来解决我的问题。谢谢 :) – murli2308