javascript - 如何独立调用 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
解决方案
您可以做的是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 提到的那样。
推荐阅读
- linux - Shell 脚本:MongoDB 转储
- laravel - 在 AWS 实例上使用 redis 时,laravel echo 服务器不监听事件
- windows - 如何在 Windows 驱动器上单独共享和保护单独的文件夹
- swift - Swift UI 瀑布网格/Firestore
- python - 有预定义的颜色列表吗?所以我可以通过索引访问颜色
- c++ - fromRequest 模板,Drogon C++ 框架的特化问题
- javascript - 如何将视频源与音频结合起来?
- javascript - 在 Javascript 中导入
- python - 如何在 DataFrame 的所有列中查找元素的所有出现?
- c++ - 当前标准是否保证在完整对象的初始化抛出异常时调用子对象的析构函数