I have this table and chart with scattergraph:
https://jsfiddle.net/horacebury/bygscx8b/6/
And I'm trying to update the positions of the scatter dots when the values in the second table column change.
Based on this SO I thought I could just use a single line (as I'm not changing the number of points, just their positions):
https://stackoverflow.com/a/16071155/71376
However, this code:
svg.selectAll("circle")
.data(data)
.transition()
.duration(1000)
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
});
Is giving me this error:
Uncaught TypeError: svg.selectAll(...).data is not a function
The primary issue is that:
svg.selectAll("circle") is not a typical selection as you have redefined svg to be a transition rather than a generic selection:
var svg = d3.select("#chart").transition();
Any selection using this svg variable will return a transition (from the API documentation), for example with transition.selectAll():
For each selected element, selects all descendant elements that match
the specified selector string, if any, and returns a transition on the
resulting selection.
For transitions, the .data method is not available.
If you use d3.selectAll('circle') you will have more success. Alternatively, you could drop the .transition() when you define svg and apply it only to individual elements:
var svg = d3.select('#chart');
svg.select(".line").transition()
.duration(1000).attr("d", valueline(data));
...
Here is an updated fiddle taking the latter approach.
Also, for your update transition you might want to change scale and values you are using to get your new x,y values (to match your variable names):
//Update all circles
svg.selectAll("circle")
.data(data)
.transition()
.duration(1000)
.attr("cx", function(d) {
return x(d.date);
})
.attr("cy", function(d) {
return y(d.close);
});
}
Related
I am using j3.ds to deploy some data on a pie chart. It seems to work fine and it updates correctly when I introduce new data. The thing is, I wanted to do the transition when updating smoothly, like here:
https://www.d3-graph-gallery.com/graph/pie_changeData.html
For some reason it is not working when I introduce the merge and transition, can somebody help with the task? thanks in advance
update();
function update() {
var data = d3.selectAll('.values').nodes();
var pie = d3.pie() //we create this variable, for the values to be readeable in the console
.value(function(d) {return d.innerHTML; })(data);
console.log("pie = ",pie)
var u = svg.selectAll("path")
.data(pie)
console.log("u = ",u)
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function
u
.enter()
.append('path')
.merge(u)
.transition()
.duration(2000)
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', function(d,i){ return color[i] })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 1)
}
Merge combines one selection with another as follows:
selectionCombined = selection1.merge(selection2);
You aren't providing a second selection, so you aren't merging anything. The selection you do have you are calling .merge() on is the enter selection, returned by .enter() - unless you add new slices to the pie, this will be empty every update after the first. As you aren't merging anything with the enter selection, post merge the selection is still empty.
The enter selection is used to create elements so that for every item in the data array there is one corresponding element in the DOM - as you already have slices, only the update selection is not empty.
The update selection is that returned by .data(), it contains existing elements which correspond to items in the data array. You want to merge this selection with the one returned by .enter():
var update = svg.selectAll("path")
.data(pie)
var enter = update.enter()
.append('path')
var merged = update.merge(enter)
However, a transition needs a start value and an end value. In your case you are trasitioning the d attribute of a path. On update the start value is the path's current d and the end value is a d representing the new value for the slice. On initial entry, what is the value that the transition should start from? It may be more appropriate to only transition on update:
var arc = d3.arc().innerRadius(0).outerRadius(radius);
var update = svg.selectAll("path")
.data(pie)
var enter = update.enter()
.append('path')
// Set initial value:
.attr('d', arc)
// If these values don't change, set only on enter:
.attr('fill', function(d,i){ return color[i] })
.attr("stroke", "black")
.style("stroke-width", "2px")
update.transition()
// transition existing slices to reflect new data.
.attr('d',arc)
Note: transitioning paths can be difficult - you'll notice the deformity to the pie in the transition in your example. This is because of how the d attribute string is interpolated. If you want to preserve the radius a different approach is needed in applying the transition.
My code looks like the following (omitting the scales that I'm using):
// Nesting data attaching "name" as data key.
var dataNest = d3.nest()
.key(function(d) { return d.name; })
.entries(data);
// Defining what the transition for the path.
var baseTransition = d3.transition()
.duration(1000)
.ease(d3.easeLinear);
// Bind data to SVG (use name as key).
var state = svg2
.selectAll(".line2")
.data(dataNest, function(d, i) { return d.key; });
// Enter data join.
state.enter()
.append("path")
.attr("class", "line2");
// Set transition and define new path being transition to.
state.transition(baseTransition)
.style("stroke", "#000")
.style("fill", "none")
.attr("id", function(d) { return 'tag'+d.key.replace(/\s+/g, ''); })
.attr("d", function(d) { return line(d.values); });
state.exit().remove();
I'm mostly following this example in which the transitions are working on top of a drop down list. However, while the code I have above displays paths, it does not transition between the paths. Are there any obvious flaws in my approach?
EDIT: I have a more concrete example of what I want to do with this JSFiddle. I want to transition from data to data2 but the code immediately renders data2.
I've made a plunker that updates data from one csv file to another, the yaxis updates accordingly but the rectangles don't.
The .attr("height", function(d) { return Math.abs(y(d[0])) - y(d[1]); }); portion of the code still has the old data from the previous file (I'm guessing).
I'm guessing this is because I haven't declared .data(series) in the updateData() function, I remember doing something like this in another chart
g.selectAll(".bar").data(series).transition()
etc...
but this doesn't work in this chart.
I can't figure it out, any help is appreciated!
The problem was that you didn't join the new data to existing bars.
To make this work well, you will want to specify a key for category of data when you join the series to the g elements to ensure consistency (although I notice that category-1 is positive in the first dataset, and negative in the second, but this is test data i guess)
Here's the updated plunkr (https://plnkr.co/edit/EoEvVWiTji7y5V3SQTKJ?p=info), with the relevant code highlighted below:
g.append("g")
.selectAll("g")
.data(series, function(d){ return d.key }) //add function to assign a key
.enter().append("g")
.attr("class", "bars") //so its easy to select later on
//etc
...
function updateData() {
d3.csv("data2.csv", type, function(error, data) {
///etc
let bars = d3.selectAll(".bars") //select the g elements
bars.data(series, function(d){ return d.key }) //join the new data
.selectAll(".bar")
.data(function(d) { return d; })
.transition()
.duration(750)
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return Math.abs(y(d[0])) - y(d[1]); });
I'm getting to grips with D3.js. I would like to write a function that draws one set of dots with one set of data, then another set of dots with another set of data.
I have written this, but the second set of dots is over-writing the first set of dots! How can I rewrite it without the selectAll so that I correctly end up with two sets of dots?
function drawDots(mydata) {
focus.selectAll(".dot").data(mydata)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 3.5);
}
drawDots(data[0]);
drawDots(data[1]);
(NB: This is a simplification. Basically I want to know how to use .enter() with a function call.)
you need to give two sets of data distinct class names. Right now both get tagged with the same class (".dot"), but if they represent different sets, you also need to be able to distinguish between them. E.g.:
function drawDots(mydata, name) {
focus.selectAll(".dot"+"."+name).data(mydata)
.enter().append("circle")
.attr("class", "dot" + " " + name)
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 3.5);
}
drawDots(data[0], "set1");
drawDots(data[1], "set2");
I've only used d3js for building force graphs, but I think in your case you need to add the nodes first to the visualization, then invoke enter() and then fetch what is in the graph.
function drawDots(mydata)
{
myD3Object.nodes(myData).start();
focus.selectAll(".dot").data(myD3Object.nodes())
.enter().append("circle")
.attr("class", "dot")
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 3.5);
}
I'm adding nodes to a force layout graph like this:
var node = vis.selectAll("circle.node")
.data(nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 5)
.style("fill", function(d) { return fill(d.group); })
.call(force.drag);
Is there a way to add compound SVG elements as nodes? I.e. I want to add a hyperlink for each circle, so I'd need something like this:
<circle ...></circle>
Creating a "compound" element is as simple as appending one or more children to another element. In your example, you want to bind your data to a selection of <a> elements, and give each <a> a single <circle> child.
First of all, you need to select "a.node" instead of "circle.node". This is because your hyperlinks are going to be the parent elements. If there isn't an obvious parent element, and you just want to add multiple elements for each datum, use <g>, SVG's group element.
Then, you want to append one <a> element to each node in the entering selection. This creates your hyperlinks. After setting each hyperlink's attributes, you want to give it a <circle> child. Simple: just call .append("circle").
var node = vis.selectAll("a.node")
.data(nodes);
// The entering selection: create the new <a> elements here.
// These elements are automatically part of the update selection in "node".
var nodeEnter = node.enter().append("a")
.attr("class", "node")
.attr("xlink:href", "http://whatever.com")
.call(force.drag);
// Appends a new <circle> element to each element in nodeEnter.
nodeEnter.append("circle")
.attr("r", 5)
.style("fill", function(d) { return fill(d.group); })
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
Remember that D3 primarily operates on selections of nodes. So calling .append() on the entering selection means that each node in the selection gets a new child. Powerful stuff!
One more thing: SVG has its own <a> element, which is what I was referring to above. This is different from the HTML one! Typically, you only use SVG elements with SVG, and HTML with HTML.
Thanks to #mbostock for suggesting that I clarify the variable naming.
Reply to Jason Davies (since stackoverflow limits the length of reply comments…): Excellent answer. Be careful with the method chaining, though; typically you want node to refer to the outer anchor element rather than the inner circle element. So I'd recommend a small variation:
var node = vis.selectAll("a.node")
.data(nodes)
.enter().append("a")
.attr("class", "node")
.attr("xlink:href", "http://whatever.com")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(force.drag);
node.append("circle")
.attr("r", 5)
.style("fill", function(d) { return fill(d.group); });
I've also replaced the circle's cx and cy attributes with a transform on the containing anchor element; either one will work. You can treat svg:a elements as svg:g (both are containers), which is nice if you want to add labels later.