问题
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.
My code:
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);
回答1:
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.
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);
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
The enter
function is only called if [dataset]
has changed. The .attr("d", line)
logic is called on both enter and update.
来源:https://stackoverflow.com/questions/52028595/how-to-use-enter-data-join-for-d3-line-graphs