How do I properly add transitions to D3 Polygons? - d3.js

Original Code can be found at: http://bl.ocks.org/Guerino1/451f4c47842967dd813c8a64b24f7686
Problem: Applying .transition() code to different polygon sets appears to yield different results.
The following portion of the code seems to work as expected. Applying a transition causes the chevrons to transition onto the svg canvas, from left to right...
svgChevronsCanvas.selectAll("a")
.data(dataSet)
.enter().append("a")
.attr("xlink:href", function(d) { return d.link; })
.append("svg:polygon")
.attr("id", function(d,i){ return ("chevron_" + selectString.replace(/ /g,'_').replace(/#/g,'') + "_index_" + i); })
.attr("originalcolor", polygonPrimaryColor)
//.style("stroke","blue")
//.style("stroke-width",1)
.style("fill", polygonPrimaryColor)
.attr("points", chevronOrigin)
.on('mouseover', chevronMouseOver)
.on("mouseout", chevronMouseOut)
.on("click", chevronMouseOut)
.transition() // <------------------- TRANSITION HERE
.duration(3000)
.attr("points", calculateChevron);
The following code, which attempts to follow the same pattern as above does not seem to work as expected. Given the transition, I would expect the textboxes (in light blue below the chevrons), which are also drawn using D3 polygons, to transition onto their svg canvas from left to right, just like the chevron polygons in the above code...
svgTextboxesCanvas.selectAll("a")
.data(dataSet)
.enter().append("a")
.attr("xlink:href", function(d) { return d.link; })
.append("svg:polygon")
.attr("id", function(d,i){ return ("textbox_" + selectString.replace(/ /g,'_').replace(/#/g,'') + "_index_" + i); })
.attr("originalcolor", textboxColor)
.style("stroke", textboxColor)
.style("stroke-width",1)
.style("fill", textboxColor)
.attr("points", textboxesOrigin)
.on('mouseover', textboxMouseOver)
.on("mouseout", textboxMouseOut)
.on("click", textboxMouseOut)
.transition()
.duration(3000)
.attr("points", calculateTextbox);
Question: How do I properly add transitions to the D3 polygons that are built to look like rectangles (below the chevrons), in the latter set of code, and make them transition into the page just like the dark blue chevrons above them?

In the original code:
Make
var chevronGapSpace = 5;//this is the distance between each rectangle.
var slantDepth = 0;//to make the polygon rectangle.
Next, to make rectangle transition inside function calculateChevron change the calculations accordingly:
function calculateChevron(d, i){
return [
[(svgMargin) + i*(chevronDistance),chevronTopOffset],
[(svgMargin + chevronWidth - slantDepth) + i*(chevronDistance),chevronTop],
[(svgMargin + chevronWidth - slantDepth) + i*(chevronDistance),chevronPointY],
[(svgMargin + chevronWidth - slantDepth) + i*(chevronDistance),chevronBottom],
[(svgMargin) + i*(chevronDistance),chevronBottom],
[(svgMargin + slantDepth) + i*(chevronDistance),chevronPointY]
];
};
working code here

Related

D3 circle element remains when mouse over on data update

I have a D3 timeseries chart made up of line path and at each data point i use a circle which is appended to the lines. The circles have a mouse enter event attached to it and when the mouse is moved over the circle it displays the tooltip with the information about that data point and i also change the class of the circle so that it looks highlighted.
The problem i have got is, when the mouse is over the circle and the circle is highlighted and the tooltip is showing, at the same time if i get some new data and the chart is updated, the circle my mouse is over does not disappear even when the mouse is removed off the circle and it shows that circle hanging in the middle without being attached to any line.
I have attached the image of the chart showing the problem.
Any help to fix this problem will be highly appreciated.
Image showing d3 issue
Here's the jsfiddle code showing the issue. Try pointing your mouse to the circle and wait for the chart to update every 5 seconds
(Moving this from the comment section)
Take a look at this: https://jsfiddle.net/xvLgq8mn/
In the updateChart function you select by the circle class:
// update the circles at each data points
svg.selectAll('.circle') // here you correctly select all with the circle class
.data(this.props.data)
.attr('class', 'circle all')
.transition()
.duration(500)
.attr('cx', (d) => { return this.axis.x(d.time);})
.attr('cy', (d) => { return this.axis.y(d.count);});
but here, on mouseover, you remove the circle class and replace it with circle--highlight:
group.selectAll()
.data(this.props.data)
.enter().append('circle')
.attr('class', 'circle all')
.attr('cx', (d) => { return this.axis.x(d.time);})
.attr('cy', (d) => { return this.axis.y(d.count);})
.attr('r', 4)
.on('mousemove', function(d) {
// START: Show tooltip
div.transition()
.duration(1000)
.style('opacity', 1);
div.html('<div class="date--time">'
+ d.time
+ '</div><div class="count">' + d.count + ' incidents</div>')
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pageY - 70) + 'px');
d3.select(this)
.attr('r', 6)
.attr('class', 'circle--highlight'); // here you change the class from circle all
// to just circle--highlight,
// so when you are hovering a circle and the chart changes,
// the circle you have hovered won't be updated because
// it won't be selected due to the class difference
// END: Show tooltip
})
.on('mouseleave', function() {
// hide tooltip and return the circles to original style
div.transition()
.duration(500)
.style('opacity', 0);
// set the circle back to normal
d3.select(this)
.attr('r', 4)
.attr('class', 'circle all');
});
So a solution would be to also add the circle class along with the circle--highlight like this:
d3.select(this)
.attr('r', 6)
.attr('class', 'circle circle--highlight');
Or change your select in the updateChart like this:
svg.selectAll('circle')
but that would need many more adjustments to your script in order for it to work as expected.
Hope this helps! Good luck!

How do I add a transition delay between multiple individual transitioning polygons in D3?

The original Code can be found at: http://bl.ocks.org/Guerino1/3a51eeb95d3a8345bc27370e8c9d5b77
I have numerous polygons that are transitioning onto an svg canvas (from left to right, at the bottom of the HTML page).
The code I use to create an transition the chevrons leverages D3 Polygon:
// Create Polygons for SDLC
svgCanvas.selectAll("a")
.data(dataSet)
.enter().append("a")
.attr("xlink:href", function(d) { return d.link; })
.append("svg:polygon")
//svgCanvas.selectAll("polygon")
//.data(dataSet)
//.enter().append("polygon")
.attr("id", function(d,i){ return (selectString.replace(/ /g,'_').replace(/#/g,'') + "_index_" + i); })
.attr("originalcolor","violet")
.style("stroke","blue")
.style("fill","violet")
.style("stroke-width",2)
.attr("points", origin)
.on('mouseover', chevronMouseOver)
.on("mouseout", chevronMouseOut)
.on("click", chevronMouseOut)
.transition() // <------- TRANSITION STARTS HERE --------
.duration(3000)
.attr("points", calculateChevron);
Currently, all polygons transition into the svg canvas, together. I'd like to put a delay between each of them, so that it looks more like dealing from a deck of cards, one at a time.
How would I properly add a D3 delay to make this happen?
Thanks for any help you can offer.
try this..
.transition() // <------- TRANSITION STARTS HERE --------
.delay(function(d,i){ return 100*i; })
.duration(3000)
.attr("points", calculateChevron);

d3js update redraw stacked bar graph

I am trying to make a stacked bar graph through d3js and have it update when new data is passed through an update function. I call this update function to initially call the graph and it works fine. However, when I change the data and call it again, it erases all the "rect" elements from the graph (When I console log the data, it appears to be passing through). How can I make the graph be redrawn appropriately? I have tried experimenting with the .remove() statement at the beginning, but without it the data doesn't pass through when the bars are redrawn.
function update(my_data) {
svg.selectAll(".year").remove();
var year = svg.selectAll(".year")
.data(my_data)
.enter().append("g")
.attr("class", "year")
.attr("transform", function(d) { return "translate(" + x0(d.Year) + ",0)"; });
var bar = year.selectAll(".bar")
.data( function(d){ return d.locations; });
bar
.enter().append("rect")
.attr("class", "bar")
.attr("width", x0.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
}
update(data);
It's hard to tell exactly what you're doing cause your question doesn't include the data or the DOM. It would help if you included a link to a work-in-progress jsFiddle or something.
If I had to guess what's going wrong, it looks like you're doing a nested join where each year gets bound to a g element and then each location gets bound to a rect inside each g element.
The issue is likely you are only specifying the enter behavior, but not the update behavior or the exit behavior. As a result, when you try to redraw, nothing updates and nothing exits - but new data elements will get added.
It would seem that is why you have to add the selectAll().remove() to get anything to redraw. By removing everything, all the data elements will trigger the enter condition and get added again.
Take a look at these tutorials to better understand how the enter/update/exit pattern works and how nested joins work.
General Update Pattern: https://bl.ocks.org/mbostock/3808218
Nested Selections: https://bost.ocks.org/mike/nest/
Also, here is a jsFiddle I wrote some time ago to demonstrate how to use nested selections and the general update pattern together:
https://jsfiddle.net/reblace/bWp8L/
var series = svg.selectAll("g.row").data(data, function(d) { return d.key; });
/*
* This section handles the "enter" for each row
*/
// Adding a g element to wrap the svg elements of each row
var seriesEnter = series.enter().append("g");
seriesEnter
.attr("class", "row")
.attr("transform", function(d, i){
return "translate(" + margin.left + "," + (margin.top + (span*i)) + ")";
})
.attr("opacity", 0).transition().duration(200).attr("opacity", 1);
// Adding a text label for each series
seriesEnter.append("text")
.style("text-anchor", "end")
.attr("x", -6)
.attr("y", boxMargin + (boxDim/2))
.attr("dy", ".32em")
.text(function(d){ return d.key; });
// nested selection for the rects associated with each row
var seriesEnterRect = seriesEnter.selectAll("rect").data(function(d){ return d.values; });
// rect enter. don't need to worry about updates/exit when a row is added
seriesEnterRect.enter().append("rect")
.attr("fill", function(d){ return colorScale(d)})
.attr("x", function(d, i){ return i*span + boxMargin; })
.attr("y", boxMargin)
.attr("height", boxDim)
.attr("width", boxDim);
/*
* This section handles updates to each row
*/
var seriesUpdateRect = series.selectAll("rect").data(function(d){ return d.values});
// rect update (Will handle updates after enter)
// rect enter
seriesUpdateRect.enter().append("rect")
.attr("x", function(d, i){ return i*span + boxMargin; })
.attr("y", boxMargin)
.attr("height", boxDim)
.attr("width", boxDim);
// rect enter + update
seriesUpdateRect
.attr("fill", function(d){ return colorScale(d)});
// Exit
seriesUpdateRect.exit();
/*
* This section handles row exit
*/
series.exit()
.attr("opacity", 1)
.transition().duration(200).attr("opacity", 0)
.remove();

Appending another element when a sibling element's transition ends

I have a bar chart, which I am using transitions to animate the heights of rect elements like so:
//Create a layer for each category of data that exists, as per dataPointLegend values
//e.g. DOM will render <g class="successful"><g>
layers = svg.selectAll('g.layer')
.data(stacked, function(d) {
return d.dataPointLegend;
})
.enter()
.append('g')
.attr('class', function(d) {
return d.dataPointLegend;
})
//transform below is used to shift the entire layer up by one pixel to allow
//x-axis to appear clearly, otherwise bars inside layer appear over the top.
.attr('transform', 'translate(0,-1)');
//Create a layer for each datapoint object
//DOM will render <g class="successful"><g></g><g>
barLayers = layers.selectAll('g.layer')
.data(function(d) {
return d.dataPointValues;
})
.enter()
.append('g');
//Create rect elements inside each of our data point layers
//DOM will render <g class="successful"><g><rect></rect></g></g>
barLayers
.append('rect')
.attr('x', function(d) {
return x(d.pointKey);
})
.attr('width', x.rangeBand())
.attr('y', height - margin.bottom - margin.top)
.attr('height', 0)
.transition()
.delay(function(d, i) {
return i * transitionDelayMs;
})
.duration(transitionDurationMs)
.attr('y', function(d) {
return y(d.y0 + d.pointValue);
})
.attr('height', function(d) {
return height - margin.bottom - margin.top - y(d.pointValue)
});
I then have a further selection used for appending text elements
//Render any point labels if present
//DOM will render <g><g><rect></rect><text></text></g></g>
if (width > miniChartWidth) {
barLayers
.append('text')
.text(function(d) {
return d.pointLabel
})
.attr('x', function(d) {
return x(d.pointKey) + x.rangeBand() / 2;
})
.attr('y', function(d) {
var textHeight = d3.select(this).node().getBoundingClientRect().height;
//Position the text so it appears below the top edge of the corresponding data bar
return y(d.y0 + d.pointValue) + textHeight;
})
.attr('class', 'data-value')
.attr('fill-opacity', 0)
.transition()
.delay(function(d, i) {
return i * transitionDelayMs + transitionDurationMs;
})
.duration(transitionDurationMs)
.attr('fill-opacity', 1);
}
This fades in the text elements nicely after all the rects have finished growing in height. What I wondered, was whether its possible to append a text element to the corresponding layer as each bar finishes its transition?
I have seen the answer on this SO - Show text only after transition is complete d3.js
Which looks to be along the lines of what I am after, I tried adding an .each('end',...) in my rect rendering cycle like so
.each('end', function(d){
barLayers
.append('text')
.text(function() {
return d.pointLabel
})
.attr('x', function() {
return x(d.pointKey) + x.rangeBand() / 2;
})
.attr('y', function() {
var textHeight = d3.select(this).node().getBoundingClientRect().height;
//Position the text so it appears below the top edge of the corresponding data bar
return y(d.y0 + d.pointValue) + textHeight;
})
.attr('class', 'data-value')
.attr('fill-opacity', 0)
.transition()
.delay(function(d, i) {
return i * transitionDelayMs + transitionDurationMs;
})
.duration(transitionDurationMs)
.attr('fill-opacity', 1);
});
But I end up with lots of text elements for each of my g that holds a single rect for each of my datapoints.
I feel like I'm close, but need some assistance from you wise people :)
Thanks
whateverTheSelectionIs
.each('end', function(d){
barLayers
.append('text')
.each runs separately for every element in your selection, and inside the each you're adding text elements to every barLayer (barLayers). So you're going to get a (barLayers.size() * selection.size()) number of text elements added overall. You need to add only one text element in the each to the right bar / g.
The below is a fudge that might work. It's tricky because the text you want to add is a sibling of the rects in the selection that calls the .each function..., d3.select(this.parentNode) should move you up to the parent of the rect, which would be the right barLayer.
whateverTheSelectionIs
.each('end', function(d,i){
d3.select(this.parentNode)
.append('text')

Trouble adding and removing elements in d3

My goal is to remove a data point from my bar chart.
It will then update itself:
Update X and Y axis
Update the actual bar chart
Update the legend
Issues I am having:
When I exit().remove() the rectangles in my graph, the code also gets rid of the rectangles in the legend. When I try to enter() the rectangles in my legend, they do not appear. I am not sure what is happening here, but I am not being successful in adding and removing elements due to data changes. Any help would be appreciated.
Code snippet of where I think I am having issues:
This is the part that also deletes the rectangles in the legend (I am not sure if I should do this here or in the enter/update/delete part of the legend)
The code below is executed right after the user clicks the "delete all" button. My intent here is to only delete one bar (the one named "ALL") and update the chart.
//Select rectangles
var bars = svg.selectAll("rect")
.data(dataset, function(d) { return d.State; });
//Enter rectangles
bars.enter()
.append("rect")
.style("fill", function(d,i) { return color(i) })
.attr("x", function(d) { return xScale(d.State); })
.attr("y", function(d) { return yScale(d.CustomerCount) })
.attr("width", xScale.rangeBand()) //returns rangeRoundBands width
.attr("height", function(d) { return h - yScale(d.CustomerCount) });
//Update rectangles
bars.transition()
.duration(1000)
.style("fill", function(d,i) { return color(i) })
.attr("x", function(d) { return xScale(d.State); })
.attr("y", function(d) { return yScale(d.CustomerCount) })
.attr("width", xScale.rangeBand()) //returns rangeRoundBands width
.attr("height", function(d) { return h - yScale(d.CustomerCount) });
//Exit rectangles
bars.exit()
.transition()
.duration(500)
.attr("x", w)
.remove();
Here is entire the code:
http://plnkr.co/edit/Nue5bocQsI4E6D5wfNSP
Here is the slightly smaller code:
I tried to reduce the code as much as possible but it is still pretty big.
http://jsfiddle.net/aNQWV/
In the part where you update the data you say:
var bars = svg.selectAll("rect")
.data(dataset, function(d) { return d.State; });
The problem is that at this point the svg contains two kind of rects. One kind corresponds to the bars, and the other ones are part of the legend. This means that you are joining the new data to this mix of rects, while actually you wanted to join the new data with the bars only.
So, you need a more specific selector that targets only the bar rects. The typical approach is to add a class to those rects when you create them:
svg.selectAll(".bar")
.data(input)
.enter().append("rect")
.attr("class", "bar");
Then in the part where you update the data you would say:
var bars = svg.selectAll(".bar")
.data(dataset, function(d) { return d.State; });

Resources