I'm new to d3.js and still a beginner in javascript in general. I've got d3 correctly drawing a single SVG rectangle based on a single value in an array. When I increase the value of the number in the area via an input field and then call the reDraw function, the rectangle changes to the new size for just a second and then switches back to the initial size. I'm thinking I must have a scoping problem, but can't figure it out. Any ideas?
var dataset, h, reDraw, svg, w;
w = 300;
h = 400;
dataset = [1000];
// Create SVG element
svg = d3.select("#left").append("svg").attr("width", w).attr("height", h);
// set size and position of bar
svg.selectAll("rect").data(dataset).enter().append("rect").attr("x", 120).attr("y", function(d) {
return h - (d / 26) - 2;
}).attr("width", 60).attr("height", function(d) {
return d / 26;
}).attr("fill", "rgb(3, 100, 0)");
// set size and position of text on bar
svg.selectAll("text").data(dataset).enter().append("text").text(function(d) {
return "$" + d;
}).attr("text-anchor", "middle").attr("x", 150).attr("y", function(d) {
return h - (d / 26) + 14;
}).attr("font-family", "sans-serif").attr("font-size", "12px").attr("fill", "white");
// grab the value from the input, add to existing value of dataset
$("#submitbtn").click(function() {
localStorage.setItem("donationTotal", Number(localStorage.getItem("donationTotal")) + Number($("#donation").val()));
dataset.shift();
dataset.push(localStorage.getItem("donationTotal"));
return reDraw();
});
// redraw the rectangle to new size
reDraw = function() {
return svg.selectAll("rect").data(dataset).attr("y", function(d) {
return h - (d / 26) - 2;
}).attr("height", function(d) {
return d / 26;
});
};
You need to tell d3 how to match new data to existing data in the reDraw function. That is, you're selecting all rectangles in reDraw and then binding data to it without telling it the relation between the old and the new. So after the call to data(), the current selection (the one you're operating on) should be empty (not sure why something happens for you at all) while the enter() selection contains the new data and the exit() selection the old one.
You have several options to make this work. You could either operate on the enter() and exit() selections in your current setup, i.e. remove the old and add the new, or restructure your data such that you're able to match old and new. You could for example use an object with appropriate attributes instead of a single number. The latter has the advantage that you could add a transition from the old to the new size.
Have a look at this tutorial for some more information on data joins.
Edit:
Turns out that this was actually not the issue, see comments.
Related
Refer to Inline Labels in d3 v4.0.0-alpha 9,
label.append("rect", "text")
.datum(() => this.nextSibling.getBBox())
.attr('x', d => (d.x - labelPadding))
.attr('y', d => (d.y - labelPadding))
.attr('width', d => (d.width + (2 * labelPadding)))
.attr('height', d => (d.height + (2 * labelPadding)));
It will append a rect to text by access the element inside the datum() via this.
A label is rendered for each point in each series. Beneath this label, a white rectangle is added, whose size and position is computed automatically using element.getBBox plus a little bit of padding. The resulting label is thus legible
According to D3 v3 set datum, we should create a new selection that's not bound to the data for later use in version 4 (eg. v4.7.4). I tried to create the new selection like following, but seem like the bbox is single object instead of multiple object should be loop through in datum as above code in d3 v4.0.0-alpha 9.
const newText = label.selectAll('text');
const bbox = newText.node().getBBox();
label.append('rect', 'text')
.datum(() => bbox)
.attr('x', d => (d.x - labelPadding))
.attr('y', d => (d.y - labelPadding))
.attr('width', d => (d.width + (2 * labelPadding)))
.attr('height', d => (d.height + (2 * labelPadding)));
Your snippet is not working for a simple reason. But, before addressing that, some considerations about your question:
That code from Bostock (Inline Labels) uses D3 v4, not v3.
append("rect", "text") does not append rectangles to texts. It append rectangles to the container, be it a SVG or a group element (in this particular case, a group), before the texts.
That last bullet point is important, because the texts will be always the nextSiblings in relation to the rectangles.
That being said, we come to your snippet. When you do this:
const newText = label.selectAll('text');
const bbox = newText.node().getBBox();
You are actually doing just this:
const bbox = label.selectAll('text').node().getBBox();
And your datum function will end up being:
.datum(() => label.selectAll('text').node().getBBox();)
Well, that is substantially different from Bostock's code, since this...
label.selectAll('text').node()
... will select all text elements but will return only to the first one in the DOM. That happens because of node(), which:
Returns the first (non-null) element in this selection. (emphasis mine)
On the other hand, in Bostock's code, this...
.datum(() => this.nextSibling.getBBox())
... will point to a different DOM element at each iteration, because this.nextSibling will be a different text element every time (which, as we just saw in the beginning of this answer, is the nextSibling of the corresponding rectangle).
I've been experimenting with animation.
It's very simple to animate an object across the canvas by clearing the entire canvas and redrawing it in a new location every frame (or "tick"):
// Inside requestAnimationFrame(...) callback
// Clear canvas
canvas.selectAll('*').remove();
// ... calculate position of x and y
// x, y = ...
// Add object in new position
canvas.append('circle')
.attr('cx', x)
.attr('cy', y)
.attr('r', 10)
.attr('fill', '#ffffff');
Is this a bad practice or am I doing it right?
For instance, if you were making a screen full of objects moving around, is it better practice to animate them by updating their attributes (e.g., x, y coordinates) in each frame?
Or, perhaps there is some other method I'm entirely unaware of, no?
Note: my animation might include 100-200 objects in view at a time.
It is better to move them, because that is the only way you can animate without errors.
In d3.js the idea is that the objects are data-bound. Clearing and redrawing the 'canvas' is not the correct approach. Firstly its not a canvas, its a web page, and any clearing and redrawing is handled by the browser itself. You job is to bind data to SVG, basically.
You need to make use of the d3 events, enter, exit, update which handles how the SVG behaves when the databound underlying data is modified and let d3 handle the animations.
the most simple example is here: https://bost.ocks.org/mike/circles/
select your elements, and store the selction in a variable
var svg= d3.select("svg");
var circles = svg.selectAll('circle');
now we need to databind something to the circle.
var databoundCircles = circles.data([12,13,14,15,66]);
This data can be anything. Usually I would expect a list of object, but these are simple numbers.
handle how things 'are made' when data appears
databoundCircles.enter().append('circle');;
handle what happens to them when data is removed
databoundCircles.exit().remove()
handle what happens when the data is updated
databoundCircles.attr('r', function(d, i) { return d * 2; })
this will change the radius when the data changes.
And recap from that tutorial:
enter - incoming elements, entering the stage.
update - persistent elements, staying on stage.
exit - outgoing elements, exiting the stage.
so in conclusion: don't do it like you are. Make sure you are using those events specifically to handle the lifecycle of elements.
PRO TIP: if you're using a list of objects make sure you bind the data by id, or some unique identifier, or the animations might behave unusually over time. Remember you are binding data to SVG you are not just wiping and redrawing a canvas!
d3.selectAll('circle').data([{id:1},{id:2}], function(d) { return d.id; });
Make note the optional second argument, that tells us how to bind the data! very important!
var svg = d3.select("svg");
//the data looks like this.
var data = [{
id: 1,
r: 3,
x: 35,
y: 30
}, {
id: 2,
r: 5,
x: 30,
y: 35
}];
//data generator makes the list above
function newList() {
//just make a simple array full of the number 1
var items = new Array(randoNum(1, 10)).fill(1)
//make the pieces of data. ID is important!
return items.map(function(val, i) {
var r = randoNum(1, 16)
return {
id: i,
r: r,
x: randoNum(1, 200) + r,
y: randoNum(1, 100) + r
}
});
}
//im just making rando numbers with this.
function randoNum(from, to) {
return Math.floor(Math.random() * (to - from) + from);
}
function update(data) {
//1. get circles (there are none in the first pass!)
var circles = svg.selectAll('circle');
//2. bind data
var databoundCircles = circles.data(data, function(d) {
return d.id;
});
//3. enter
var enter = databoundCircles.enter()
.append('circle')
.attr('r', 0)
//4. exit
databoundCircles.exit()
.transition()
.attr('r', 0)
.remove();
//5. update
//(everything after transition is tweened)
databoundCircles
.attr('fill', function(d, i){
var h = parseInt(i.toString(16));
return '#' + [h,h,h].join('');
})
.transition()
.duration(1000)
.attr('r', function(d, i) {
return d.r * 4
})
.attr('cx', function(d, i) {
return d.x * 2;
})
.attr('cy', function(d, i){
return d.y * 2
})
;
}
//first time I run, I use my example data above
update(data);
//now i update every few seconds
//watch how d3 'keeps track' of each circle
setInterval(function() {
update(newList());
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="300">
</svg>
Is this a bad practice or am I doing it right?
Yes, it is a bad practice. In a normal circumstance I like to call it lazy coding: clearing the SVG (or whatever) and painting the dataviz again.
But, in your case, it's even worse: you will end up writing a huge amount of code (not exactly laziness, though), ignoring d3.transition(), which can easily do what you want. And that takes us to your second question:
Or, perhaps there is some other method I'm entirely unaware of, no?
Yes, as I just said, it's called transition(): https://github.com/d3/d3-transition
Then, at the end, you said:
Note: my animation might include 100-200 objects in view at a time.
First, modern browsers can handle that very well. Second, you still have to remove and repaint manually all that elements. If you benchmark the two approaches, maybe this is even worse.
Thus, just use d3.transition().
You can change the data (or the attributes) of the elements anytime you want, and "moving" (or transitioning) them to the new value calling a transition. For instance, to move this circle around, I don't have to remove it and painting it again:
var circle = d3.select("circle")
setInterval(() => {
circle.transition()
.duration(900)
.attr("cx", Math.random() * 300)
.attr("cy", Math.random() * 150)
.ease(d3.easeElastic);
}, 1000)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<circle r="10" cx="100" cy="50" fill="teal"></circle>
</svg>
I'm trying to make a pie chart with d3.js that looks like this:
Note that the labels are placed along the edges of the pie chart. Initially, I am able to draw the pie charts and properly place the text nodes (the fiddle only displays one pie chart; assume, however, that they all have data that works and is appropriate, as this one does). However, when I go to adjust the data, I can't seem to .attr(translate, transform) them to the correct region along the edge of the pie chart (or do anything to them, for that matter):
changeFunctions[i] = function (data, i) {
path.data(pie(data))
.transition()
.duration(750)
.attrTween("d", arcTween);
text.each(function (d, num) {
d3.select(this)
.text(function (t) {
return t.data.name+". "+(100 * t.data.votes/totalVotes).toFixed(0) + "%";
})
/*
.attr("transform", function (d) {
//console.log("the d", d)
var c = arc.centroid(d),
x = c[0], y = c[1],
h = Math.sqrt(x * x + y * y);
return "translate(" + (x/h * 100) + ',' + (y/h * 100) + ")";
})*/
.attr("opacity", function (t) {
return t.data.votes == 0 ? 0 : 1;
});
})
}
I have omitted the general code to draw the pie chart; it's in the jsfiddle. Basically, I draw each of the pie charts in a for loop and store this function, changeFunctions[i], in a closure, so that I have access to variables like path and text.
The path.data part of this function works; the pie chart properly adjusts its wedges. The text.each part, however, does not.
How should I go about making the text nodes update both their values and locations?
fiddle
When updating the text elements, you also need to update the data that's bound to them, else nothing will happen. When you create the elements, you're binding the data to the g element that contains the arc segment and text. By then appending path and text, the data is "inherited" to those elements. You're exploiting this fact by referencing d when setting attributes for those elements.
Probably the best way to make it work is to use the same pattern on update. That is, instead of updating only the data bound to the path elements as you're doing at the moment, update the data for the g elements. Then you can .select() the descendant path and text elements, which will again inherit the new data to them. Then you can set the attributes in the usual manner.
This requires a few changes to your code. In particular, there should be a variable for the g element selection and not just for the paths to make things easier:
var g = svg.selectAll("g.arc")
.data(pie(data));
g.enter()
.append("g").attr("class", "arc");
var path = g.append("path");
The changeFunction code changes as follows:
var gnew = g.data(pie(data));
gnew.select("path")
.transition()
.duration(750)
.attrTween("d", arcTween);
Now, to update the text, you just need to select it and reset the attributes:
gnew.select("text")
.attr("transform", function(d) { ... });
Complete demo here.
I want the actual value of each bar displayed on top in the way it's shown here
I am trying this on multi bar chart.
Can't find reference anywhere.
Duplicate of How to display values in Stacked Multi-bar chart - nvd3 Graphs
There is a fix you can implement yourself at https://gist.github.com/topicus/217444acb4204f364e46
EDIT: Copied the code if the github link gets removed:
// You need to apply this once all the animations are already finished. Otherwise labels will be placed wrongly.
d3.selectAll('.nv-multibar .nv-group').each(function(group){
var g = d3.select(this);
// Remove previous labels if there is any
g.selectAll('text').remove();
g.selectAll('.nv-bar').each(function(bar){
var b = d3.select(this);
var barWidth = b.attr('width');
var barHeight = b.attr('height');
g.append('text')
// Transforms shift the origin point then the x and y of the bar
// is altered by this transform. In order to align the labels
// we need to apply this transform to those.
.attr('transform', b.attr('transform'))
.text(function(){
// Two decimals format
return parseFloat(bar.y).toFixed(2);
})
.attr('y', function(){
// Center label vertically
var height = this.getBBox().height;
return parseFloat(b.attr('y')) - 10; // 10 is the label's magin from the bar
})
.attr('x', function(){
// Center label horizontally
var width = this.getBBox().width;
return parseFloat(b.attr('x')) + (parseFloat(barWidth) / 2) - (width / 2);
})
.attr('class', 'bar-values');
});
});
Apparently this doesn't exist yet. There is an issue (https://github.com/novus/nvd3/issues/150) that was closed because this is (apparently) hard to implement.
I am not sure what you have tried so fat, but the example in here is pretty straight forward.
.showValues(true) pretty much does the trick.
Hope it helps.
I'm working on a simple d3 example where I use d3 to place some new divs on a page, add attributes, and add data-driven styles. The part that is tripping me up is when I want to use d3 to update some styles using new data. I've pasted the code from a jsFiddle ( http://jsfiddle.net/MzPUg/15/ ) below.
In the step that originally creates the divs, I use a key function to add indexes to the elements and in the update step (the part that isn't working) I also use a key function. But what isn't clear from the d3 documentation is how the actual data join works (e.g. where are indexes stored in the DOM elements? what if there are duplicate indexes?, etc.).
So, there are obvious gaps in my knowledge, but keeping it simple here can anyone shed light on why this example is not working? Any additional info on the precise nature of data joins in d3 would be frosting on the cake. (I've already seen http://bost.ocks.org/mike/join/.)
//add a container div to the body and add a class
var thediv = d3.select("body").append("div").attr("class","bluediv");
//add six medium-sized divs to the container div
//note that a key index function is provided to the data method here
//where do the resulting index value get stored?
var mediumdivs = thediv.selectAll("div")
.data([10,50,90,130,170,210],function(d){return d})
.enter().append("div")
.style("top",function(d){return d + "px"})
.style("left",function(d){return d + "px"})
.attr("class","meddiv")
//UPDATE STEP - NOT WORKING
//Attempt to update the position of two divs
var newdata = [{newval:30,oldval:10},{newval:80,oldval:50}]
var mediumUpdate = mediumdivs.data(newdata,function(d){return d.oldval})
.style("left",function(d){return d.newval + "px"})
As far as I know, you do not update the elements that already exist. Instead, you tell D3 which elements to draw and it determines what to remove or update on the screen.
I updated your JSFiddle with working code. I have also added the code below.
//add a container div to the body and add a class
var thediv = d3.select("body").append("div").attr("class", "bluediv");
function update(data) {
var mediumdivs = thediv.selectAll("div").data(data, function(d) {
return d;
});
// Tell D3 to add a div for each data point.
mediumdivs.enter().append("div").style("top", function(d) {
return d + "px";
}).style("left", function(d) {
return d + "px";
}).attr("class", "meddiv")
// Add an id element to allow you to find this div outside of D3.
.attr("id", function(d) {
return d;
});
// Tell D3 to remove all divs that no longer point to existing data.
mediumdivs.exit().remove();
}
// Draw the scene for the initial data array at the top.
update([10, 50, 90, 130, 170, 210]);
// Draw the scene with the updated array.
update([30, 80, 90, 130, 170, 210]);
I am not sure of D3's inner workings of how it stores indexes, but you can add an id attribute to the divs you create to create unique indexes for yourself.
In the above answer an update step is needed for transition of divs with the same key. illustrative jsfiddle showing what happens with/without update function.
Update function is just selection.stuff, rather than selection.enter().stuff :
//add a container div to the body and add a class
var updateDiv = d3.select("#updateDiv").attr("class", "bluediv");
var noUpdateDiv = d3.select("#noUpdateDiv").attr("class", "bluediv");
function update(selection,data,zeroTop,withUpdate) {
//add six medium-sized divs to the container div
//note that a key index function is provided to the data method here
//where do the resulting index value get stored?
var mediumdivs = selection.selectAll("div").data(data, function(d) {
return d;
});
if(withUpdate){
mediumdivs.style("top", function(d) {
if(zeroTop){
return 0
}else{
return d + "px";
}
}).style("left", function(d) {
return d + "px";
}).attr("class", "meddiv");
}
mediumdivs.enter().append("div").style("top", function(d) {
if(zeroTop){
return 0
}else{
return d + "px";
}
}).style("left", function(d) {
return d + "px";
}).attr("class", "meddiv");
mediumdivs.exit().remove();
}
//with the update function we maintain 3 of the old divs, and move them to the top
update(updateDiv,[10, 50, 90, 130, 170, 210],false,true);
update(updateDiv,[10,50,90],true,true);
//without the update function divs are maintained, but not transitioned
update(noUpdateDiv,[10, 50, 90, 130, 170, 210],false,false);
update(noUpdateDiv,[10,50,90],true,false);
The other answers given so far use the strategy of removing and recreating divs. This isn't necessary. The problem with Al R.'s original code was just in the way it used the data key. The same data key function is used both for the old data and for the data that's newly passed in. Since in Al R.'s example, the old data was a simple array of numbers, and the new data was an array of objects with properties, no data was selected in the mediumUpdate line.
Here's one way to make the selection work:
var newdata = [10, 50];
var newdatamap = {10:30, 50:80};
var mediumUpdate = mediumdivs.data(newdata, function(d){return d;})
.style("left",function(d){return newdatamap[d] + "px";});
Here's a jsfiddle, which also changes the color of the selected divs to make the effect obvious.