As project to get to know d3.js, I’m displaying tweets on a map in real-time. Everything has worked this far, and I’m very, very pleased with the library.
On the page, I’m trying to list all languages. On hover, I want all tweets of that language to pop up. All of this is done, except some items in the list pops up the tweets of another language. A wrong one, I might add.
This is how I project the dots on the map:
points.selectAll('circle')
.data(tweets)
.enter()
.append('circle')
// Attach node to tweet, so I can use refer to the nodes later
.each(function(d) {
d.node = this;
})
.attr('r', 1);
This is how I create the list:
var data = d3.nest()
// Group by language code
.key(function(d) { return d.lang.code; })
.entries(tweets)
// Sort list by amount of tweets in that language
.sort(function(a, b) {
return b.values.length - a.values.length;
});
var items = languages_dom
// Add items
.selectAll('li')
.data(data)
.enter()
.append('li');
// Used for debugging
.attr('data-lang', function(d) {
return d.key; // Group key = language code
})
// Set text
.text(function(d) {
var dt = d.values[0];
return dt.lang.name;
})
// Mouseover handler
.on('mouseover', function(d) {
// Compare attribute with
// These values are actually different
var attr = d3.select(this).attr('data-lang');
console.log(attr, d.key);
// Pop up each node
d.values.forEach(function(d) {
d = d3.select(d.node);
d.transition()
.duration(200)
.attr('opacity', 0.5)
.attr('r', 8);
});
});
Note that the script above is run several times. d.key refers to another value later in the chain, while I’m not modifying data in that chain.
Edit 22:08
Things seems to work fine when I’m not sorting the data. At least it’s a lead.
As noted in the comments, you're overwriting d in your forEach function. Instead, you should try something like
d.values.forEach(function(p) {
d3.select(p.node)
.transition()
.duration(200)
.attr('opacity', 0.5)
.attr('r', 8);
});
Notice the forEach variable is named p instead of d.
As the data changed, the old data seems to be kept somehow.
Either way, I simply deleted the list before applying the new data:
languages_dom
.selectAll('li')
.remove();
Can’t say this is graceful, nor performant, but it gets the job done :)
Related
I'm hoping someone can spot where I'm going wrong here as I've looked at it for over 24 hours and can't see the issue.
I have a fairly complex dataviz working nicely in D3 but the final step is to 'adjust' any overlapping points - primarily so that their individual tooltips are accessible (on hover) (e.g. I don't want to consider alternatives like 'growing' the points to show their combined status).
So, imagine a pinboard where every pin is a point with hit_x and hit_y coordinates. Everything is working perfectly (filtering, updating, etc) in what I understand to be a fairly standard D3 'update' pattern. Sometimes two pins might have the same coordinates.
I thought I'd use D3 forces (for the first time) to recognise the 'colliding' pins and then adjust their positions accordingly. However, whilst I can get a simple version working on Blockbuilder. I can't get the same thing working when applied to my dataviz, even when I simplify it considerably.
I think perhaps I don't 100% understand the simulation process when using from an update pattern. My (simplified) code is pasted below, and here's in effect what I think it should do:
Appropriately loaded/formatted data is passed to update()
Prepare points ready to attach svg objects (same as 'standard' update pattern).
Prepare a simulation (and initially run it via ticked()).
Visualise the data.
Rerun the simulation so that the collisions are detected...
...during which, ticked() should notice the collisions and adjust the points by adjusting d.x and d.y accordingly until there are no overlaps.
I'm sure there's something obvious I'm missing - possibly related to whether I should pass the 'points' to the simulation or the original data. If anyone can spot it then I'd be very grateful. ¯\(ツ)/¯
function ticked() {
console.log("Ticking...");
points
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
});
}
// Update visualisation
function update(data) {
// Animation transitions
var t1 = d3.transition().duration(3000);
// Add svg group for handling/styling points later
graph.select("g.points").remove();
var pointsG = graph.append("g")
.attr('class', 'points');
// Data: Points
// Join new data with old elements
points = pointsG.selectAll("circle.point")
.data(data, function(d) {
return d;
});
// Forces
collisionSimulation = d3.forceSimulation(points)
.force('charge', d3.forceManyBody().strength(10))
.force('x', d3.forceX(function(d) {
return xScale(d.point.hit_x);
}).strength(0.5))
.force('y', d3.forceY(function(d) {
return yScale(d.point.hit_y);
}).strength(0.5))
.alphaTarget(1)
.on('tick', ticked);
console.log(collisionSimulation);
// Remove old elements not present in new data
points.exit()
.transition(t1)
.attr('class', 'exit')
.remove();
// Append new elements
points.enter()
.append('circle')
.attr('class', 'point')
.attr('cx', function(d) {
return xScale(d.point.hit_x);
})
.attr('cy', function(d) {
return yScale(d.point.hit_y);
})
.attr('r', 5)
.merge(points);
collisionSimulation.nodes(points)
.force("collide", d3.forceCollide().strength(0.5).radius(function() {
return 5;
}));
collisionSimulation.alpha(0.5).restart();
}
OK, now resolved - though I would appreciate further input on the ticked() implementation.
I imagine someone will go through the same process as me at some point, so following is what I did to get things working. The crux of it is that I had been getting confused joining the forces with the visual objects. By passing the same original data to both, the forces were then able to act on the visual objects, rather than both existing as one.
I re-read the core information about data joins. I've read this a number of times over the past few months working with D3 but for some reason, reading it again made my forces / update pattern finally make (un)sense in my head.
Similarly, despite having used a few excellent Blocks examples for reference, I came across this Medium article which made things click for me. It doesn't mean the Blocks examples aren't great - just that for some reason this article helped me.
Thereafter, I updated my code and was able to get things working. I feel like I'm still missing a little bit of 'data join' magic in my ticked() function though as it seems odd to need to 'search' for the relevant items to act on rather than use a previously built reference. I'm sure I can optimise that, but if anyone else can input then great.
Hope that helps someone else out.
function ticked() {
console.log("Ticking...");
d3.select('g.points').selectAll('circle.point')
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
// Update visualisation
function update(data) {
// Animation transitions
var t1 = d3.transition().duration(3000);
// Add svg groups for organising data elements
graph.select("g.points").remove();
var pointsG = graph.append("g")
.attr('class', 'points');
// Points
// Join new data with old elements
points = pointsG.selectAll("circle.point")
.data(data, function(d){ return d; });
// Remove old elements not present in new data
points.exit()
.transition(t1)
.attr('class', 'exit')
.remove();
// Append new elements
points.enter()
.append('circle')
.attr('class', 'point')
.attr('cx', function(d){ return xScale(d.point.hit_x); })
.attr('cy', function(d){ return yScale(d.point.hit_y); })
.attr('r', 5)
.merge(points);
// Forces
collisionSimulation = d3.forceSimulation()
.nodes(data)
.force('charge', d3.forceManyBody().strength(2))
.force('x', d3.forceX(function(d) { return xScale(d.point.hit_x); }).strength(0.5))
.force('y', d3.forceY(function(d) { return yScale(d.point.hit_y); }).strength(0.5))
.force("collide", d3.forceCollide().strength(0.5).radius(function() { return 5; }))
.on('tick', ticked);
collisionSimulation.alpha(0.5).restart();
}
I am working on a widget that shows several D3 bar charts with different values, one after the other, in a sliding carousel.
When the page loads, the bar chart animate as it should, but when the page goes on to the next chart - whether it be on click or by itself - I would like it to restart the animation again each time.
I have tried calling animateChart() in the console but this doesn't work.
I am looking for a function that I can call from the console or from another function, like animateChart(), that will reload the D3 bar chart animation.
Here is a link to my widget:
http://jsfiddle.net/alocdk/oa5tg1qu/1/
I've found where you could enhance your animateChart function.
In fact you were modifying only data that were enterring your graph.
By calling :
d3.select(svg)
.selectAll("rect")
.data(data)
.enter().append("rect")
[...]
Everything following this, will only apply on the new data.
You may want to read these to understand the pattern to follow with data update in D3.
General Update Pattern, I
General Update Pattern, II
General Update Pattern, III
Here is my shot now http://jsfiddle.net/uknynmqa/1/
I've removed the loop you were doing on all your svg, because I assumed you wanted to only animate the current one.
And your function is updating all of the data, and not only those enterring thanks to :
// Update the data for all
var join = d3.select(svg)
.selectAll("rect")
.data(data);
// Append new data.
join.enter().append("rect")
.attr("class", function (d, i) {
var low = ""
i == minIndex ? low = " low" : "";
return "bar" + " " + "index_" + i + low;
})
// Update everyone.
join.attr("width", barWidth)
.attr("x", function (d, i) {
return barWidth * i + barSpace * i;
})
.attr("y", chartHeight)
.attr("height", 0)
.transition()
.delay(function (d, i) {
return i * 100;
})
.attr("y", function (d, i) {
return chartHeight - y(d);
})
.attr("height", function (d) {
return y(d);
});
D3 is following a really specific data update pattern.
Depending on what you want to do, you can follow this. It's up to you what you want to animate or not.
// Link data to your graph and get the join
var join = svg.selectAll('rect')
.data(data);
// Update data already there
join.attr('x', 0);
// Append the new data
join.enter().append('rect')
.attr('x', 0);
// Remove exiting elements not linked to any data anymore
join.exit().remove();
// Update all resulting elements
join.attr('x', 0);
I am currently learning data visualizations with d3.js. I am using the tutorial on the d3.js site. I am at the part where the data bound to DOM elements have to retrieved. I did it exactly as they have shown, but I am not able to get the data from it.
Here is the code from the beginning:
var theData=[1,2,3]
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text("hello")
This displays:
hello
hello
hello
Now, on the site, it tells me to enter the following code to obtain the data bound i.e. 1,2 & 3.
var theData=[1,2,3]
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text(function (d) { return d; } )
Even after doing this, the page does not change,like it should to:
1
2
3
It remains the same(it keeps showing the three hello's).
How do I get the data back?
when just using this :
var theData2 = [ 1, 2, 3 ]
var p2 = d3.select("body").selectAll("p")
.data(theData2)
.enter()
.append("p")
.text( function (d) {
console.log(d);
return d; } );
It works, you're using variables with the same names which you really shouldn't do
http://jsfiddle.net/cwqwbw3u/1/
When I try your code, it works (however, I am a all for pretty javascript, so I added ';' when approriate).
I would suggest checking out the console on the browsers developers tools (perhaps there are showing errors already) and change your code to something like this:
var theData=[1,2,3];
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text(function (d) {
console.log("checking d");
console.log(d);
return d;
} );
it would be really weird if you did not see at least "checking d" in your console...
When our dataset contains more items than available DOM elements, the surplus data items are stored in a sub set of this selection called the enter selection. When you try to use enter for the second time, there are already 3 elements and so no items are stored in enter selection. You should have used the same enter selection for both tasks.
var theData=[1,2,3]
var p = d3.select("body")
.selectAll("p")
.data(theData);
p.enter()
.append("p")
.text("hello");
p.enter()
.append("p")
.text(function (d) { return d; } );
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I have a scatter graph built with d3.js. It plots circles in the graph for the spending habits of specific people.
I have a select menu that changes the specific user and updates the circles on the scatter graph.
The problem is the old circles are not removed on update.
Where are how should I use .remove() .update(), please see this plnkr for a working example
http://plnkr.co/edit/qtj1ulsVVCW2vGBvDLXO?p=info
First, Alan, I suggest you to adhere to some coding style convention to make your code readable. I know that D3 examples, and the library code per se, almost never promote code readability, but it's in your interest first, because it's much easier to maintain readable code.
Second, you need to understand how D3 works with enter, update and exit sets, when you change data. Mike Bostock's Thinking with Joins may be a good start. Unless you understand how the joins work, you won't be able to program dynamic D3 charts.
Third, here's a bug in updateScatter. name.length makes no sense because your first name variable is value. So it's not the case of deleting old data in the first place.
// Update circles for the selected user chosen in the select menu.
svg.selectAll(".markers")
.data(data.filter(function(d){ return d.FirstName.substring(0, name.length) === value;}))
.transition().duration(1000)
.attr("cx", function(d) { return xScale(d.timestamp); })
.attr("cy", function(d) { return yScale(d.price); });
Also what that weird equality comparison is d.FirstName.substring(0, name.length) === name. Your first name data is not even spaced in CSV file. Plain d.FirstName == name is fair enough. If you expect trailing spaces anyway, just trim your strings in the place where you coerce prices and dates.
This is how correct updateScatter may look look like:
function updateScatter()
{
var selectedFirstName = this.value;
var selectedData = data.filter(function(d)
{
return d.FirstName == selectedFirstName;
});
yScale.domain([
0,
d3.max(selectedData.map(function(d)
{
return d.price;
}))
]);
svg.select(".y.axis")
.transition().duration(750)
.call(yAxis);
// create *update* set
var markers = svg.selectAll(".markers").data(selectedData);
// create new circles, *enter* set
markers.enter()
.append('circle')
.attr("class", 'markers')
.attr("cx", function(d)
{
return xScale(d.timestamp);
})
.attr("cy", function(d)
{
return yScale(d.price);
})
.attr('r', 5)
.style('fill', function(d)
{
return colour(cValue(d));
});
// transition *update* set
markers.transition().duration(1000)
.attr("cx", function(d)
{
return xScale(d.timestamp);
})
.attr("cy", function(d)
{
return yScale(d.price);
});
// remove *exit* set
markers.exit().remove();
}
Fairly new to d3.js, so hoping there's something obvious that I'm missing. Have been looking at this code over and over again, not sure where it's going wrong.
I have a bargraph, which displays 28 bars. I'm trying to:
Replicate this tutorial, where new data is added to graph, and oldest data is removed.
Instead of using shift to remove data, I'd like to push to the graph/array, but only display the last 28 numbers. I'd like to use the whole array for another display. This said, I can't get the above to work.
This is a jsFiddle to the troublesome code.
I have a graph located within a group (with a unique ID, #kI1data, plan on having multiple graphs later). When that group is clicked, a value from the data array is shifted, and another pushed. The graph is then redrawn. I believe it's this redraw function that is causing an issue; it removes rectangles, but doesn't add any new ones after the first click.
graphGroup.append("g")
.attr("id", "kInv1")
.append("rect")
.attr("class", "invBack")
.attr("x", 0).attr("y", 0)
.attr("width", kI1width).attr("height", kI1height)
.attr("fill", "grey")
.on("click", dataChange); // Add/remove data, and update graph
function dataChange() {
kInvd1.shift();
kInvd1.push(30); // 30 a placeholder number
updateGraph();
};
function updateGraph() {
// Select the group containing the rectangles that need updating
// (to avoid selecting other rectangles within the svg)
var kI3dataSelect = d3.select("#kI1data").selectAll("rect").data(kInvd1, function(d) { return d; });
// Enter new data
kI3dataSelect.enter().append("rect")
.attr("x", function(d, i) { return 1 + ((i+1) * ((kI1width)/28)); })
.attr("y", function(d) { return ykI1(d); })
.attr("height", function(d) { return (kI1height) - ykI1(d); })
.attr("width", (kI1width)/28)
.attr("fill", "black");
// Update positions (shift one bar left)
kI3dataSelect
.transition().duration(100)
.attr("x", function(d, i) { return 1 + (i * ((kI1width)/28)); });
kI3dataSelect.exit()
.transition().duration(100)
.attr("x", function(d, i) { return 1 + ((i-1) * ((kI1width)/28)); })
.remove();
};
For now I'm just trying to get the newly added data to display, whilst the oldest data is removed. Once that's done, if there are any pointers on how to display just the last 28 numbers in the array, it'd be very much appreciated!
The jsFiddle shows how a new bar is added on the first click, but subsequent clicks only translate and remove data, whilst new bars are not added.
Changing your dataChange function to the following gets you new insertions and limits the over all array to 28 elements.
function dataChange() {
if (kInvd1.length >= 28) kInvd1.shift()
kInvd1.push(Math.random() * 60); // 30 a placeholder number
updateGraph();
};