我正在研究 Mike Bostock 的以下关于焦点 + 上下文缩放的示例。 https://bl.ocks.org/mbostock/1667367 。
我想知道我们是否可以将多个图表与主图链接起来。与所附图像类似的东西。我对 d3.js 很陌生,所以我可能错过了一些东西,但我找不到任何关于如何进行操作的链接。所有图表都有相同的数据点。
最佳答案
这显然取决于您的数据的组织方式。我想您有一个 data
数组,如下所示:
[ {date : ... /*x-coordinate*/
price1 : .../*first y-coordinate*/
price2 : .../*second y-coordinate*/
/* ...and as many as you like*/
},
{date : ...
price1 : ...
price2 : ... }
]
您还有一个数组,其中包含要作为 y 轴获取的字段的名称:
fields = ["price1", "price2", ...]
因此,首先要做的是提取每条单独曲线的数据。这可以按如下方式完成:
function singleCurveData(fieldId) {
return data.map(function (d) {
return {date: d.date, price: d[fieldId]};
});
}
如果您的数据组织方式不同,则只需更改此函数。基本上,它接收您想要绘制的图形的 ID,并以标准方式输出该特定图形的数据。
<小时/>现在到绘图部分。您需要与要显示的不同字段一样多的焦点
部分,每个部分包含一个区域
;以及包含许多 area2
的单个 context
部分。
var focus = svg.selectAll(".focus")
.data(fields) //associate one field id to each focus block
.enter()
.append("g")
.attr("class", "focus")
.attr("transform", function(d,i) {return "translate(" + margin.left + "," + (margin.top - i*focusHeight) + ")"});
//the above line takes care of the positioning, you need to know the target height of a focus block.
var context= ...//as before
现在我们继续绘制曲线:
focus.append("path") //append one path per focus element
.datum(function(fieldId) {return singleCurveData(fieldId)}) //only this line changes
.attr("class", "area")
.attr("d", area);
context.selectAll("path")
.data(fields) // add a "path" for each field
.enter()
.append("path") //here the datum for the path is the field Id
.datum(function(fieldId) {return singleCurveData(fieldId)})
//now the datum is the path data for the corresponding field
.attr("class", "area")
.attr("d", area2);
这应该就是全部内容了。祝你好运!
关于javascript - D3.js:上下文+焦点缩放多个图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614785/