问题描述
我试图了解如何使用带线图的数据联接.我看到的大多数示例在我们的数据连接中使用datum()而不是data(),并且在添加path元素时直接使用line函数进行映射.我认为我们更喜欢在这种情况下使用datum(),因为整个line函数都是一条单一路径.
I'm trying to understand how we can go about using data joins with line graphs. Most examples I see use datum(), rather than data() with our data join, and a direct mapping of the line function when appending the path element. I think we prefer using datum() in this case because the entire line function is sort of a single path.
不过,要想更多地了解数据联接,我想看看如何使它适用于单个折线图,但是我在下面尝试的代码片段似乎确实有效.
To understand data joins more though, I would like to see how I could make this work for a single line graph, but the snippet I try below does seem to work.
我的代码:
var dataset = [50, 80, 40, 30, 20];
var xScale = d3.scaleLinear()
.domain([0,4])
.range([0, width]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d, i) { return xScale(i); })
.y(function(d) { return yScale(d); });
// ** Works just fine, as expected **
// svg.append("path")
// .datum(dataset)
// .attr("d", line)
// .attr("class", "line");
// Does not work
svg.selectAll("path")
.datum(dataset)
.enter().append("path")
.attr("class", "line")
.attr("d", line);
推荐答案
行的窍门是,您正在构建单个svg path
,而不是像大多数情况下那样构建多个单独的svg形状条形图等其他可视化形式.
The trick with lines is that you are building a single svg path
rather than a number of individual svg shapes like you would with most other kinds of visualisations like bar charts.
因此,您需要一个单个数据项,其中包括行所需的所有点,才能使d3连接逻辑起作用:
So you need a single data item, consisting of all the points needed for your line, for the d3 join logic to work:
svg.selectAll("path")
.data([dataset])
.enter().append("path")
.attr("class", "line")
.attr("d", line);
或者,如果您要输入/更新/删除逻辑,请使用最近的(d3.join)[https://github.com/d3/d3-selection#selection_join]模式:
Or if you want enter/update/remove logic, using the recent (d3.join)[https://github.com/d3/d3-selection#selection_join] pattern:
svg.selectAll("path")
.data([dataset])
.join(
enter => enter.append("path").attr("class", "line"),
update => update,
exit => exit.remove()
)
.attr("d", line); // and other attributes that change on enter/update here
仅当 [数据集]
已更改时,才调用 enter
函数.在输入和更新上都调用 .attr("d",行)
逻辑.
The enter
function is only called if [dataset]
has changed. The .attr("d", line)
logic is called on both enter and update.
这篇关于如何对D3折线图使用Enter(数据联接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!