首页 > 解决方案 > 如何独立调用 d3.svg.line()?

问题描述

lineFunction在本例中对应于d3.svg.line()。然而,稍后lineFunction将作为带有参数的函数填充lineData,即具有 x 和 y 坐标的点列表。如何绕过lineFunction并将数据集直接包含在 中d3.svg.line()

我的方法是直接调用d3.svg.line(lineData)

//The line SVG Path we draw
var lineGraph = svg.append("path")
  .attr("d", d3.svg.line(lineData)
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate('linear'))
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");

但这没有任何意义,只要这不是接受参数的函数。我还查看了 D3 代码库,发现 line 函数确实接受输入:

export default function() {
  var x = pointX,
  // ...
  function line(data) {
    // ...
  }
  // ...
  return line;
}

这是Dimitar Danailov的一个运行示例

var width = 400;
var height = 400;

var svg = d3.select('body').append('svg');
svg.attr('width', width);
svg.attr('height', height);

//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; })
  .interpolate('linear');

//The data for our line
var lineData = [ 
  { "x": 1,   "y": 5},  
  { "x": 20,  "y": 20},
  { "x": 40,  "y": 10}, 
  { "x": 60,  "y": 40},
  { "x": 80,  "y": 5},  
  { "x": 100, "y": 60}
];
  
//The line SVG Path we draw
var lineGraph = svg.append("path")
  .attr("d", lineFunction(lineData))
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");
svg {
  font-family: "Helvetica Neue", Helvetica;
}

.line {
  fill: none;
  stroke: #000;
  stroke-width: 2px;
}
<script src="//d3js.org/d3.v3.min.js"></script>

资料来源:https ://bl.ocks.org/dimitardanailov/6f0a451d4457b9fa7bf6e0dddcd0f468

更多示例:https ://www.dashingd3js.com/svg-paths-and-d3js

标签: javascriptd3.jssvg

解决方案


您可以做的是d3.svg.line()在配置后调用,例如:

var lineGraph = svg.append("path")
  .attr("d", d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate('linear')(lineData))

所以修改后的片段看起来像这样:

var width = 400;
var height = 400;

var svg = d3.select('body').append('svg');
svg.attr('width', width);
svg.attr('height', height);


//The data for our line
var lineData = [ 
  { "x": 1,   "y": 5},  
  { "x": 20,  "y": 20},
  { "x": 40,  "y": 10}, 
  { "x": 60,  "y": 40},
  { "x": 80,  "y": 5},  
  { "x": 100, "y": 60}
];
  
//The line SVG Path we draw
var lineGraph = svg.append("path")
  .attr("d", d3.svg.line()
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; })
  .interpolate('linear')(lineData))
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");
svg {
  font-family: "Helvetica Neue", Helvetica;
}

.line {
  fill: none;
  stroke: #000;
  stroke-width: 2px;
}
<script src="//d3js.org/d3.v3.min.js"></script>

编辑:请注意,问题和答案使用d3.svg.line()的是 d3 v3。对于更高版本,您可以使用d3.line(),并省略interpolate,就像下面@uzay95 提到的那样。


推荐阅读