d3.js - transform & transition, multiple lines - javascript

I have followed the instructions at: http://bost.ocks.org/mike/path/ for creating and animating single graphs with single lines.
And, figured out how to create multiple lines in a graph: Drawing Multiple Lines in D3.js
Main Issue: I am having a hard time transitioning multiple lines after I shift & push in new data into my data array.
I create the N lines with: (time: epoch time, steps forward)
var seriesData = [[{time:1335972631000, value:23}, {time:1335972631500, value:42},...],
[{time:1335972631000, value:45}, {time:1335972631500, value:13},...],
[{time:1335972631000, value:33}, {time:1335972631500, value:23},...}],
[...],[...],...
];
var seriesColors = ['red', 'green', 'blue',...];
line = d3.svg.line()
.interpolate(interpolation)
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.value); });
graphGroup.selectAll(".line")
.data(seriesData)
.enter().append("path")
.attr("class", "line")
.attr("d", line)
.style('stroke', function(d, i) { return seriesColors[i]; })
.style('stroke-width', 1)
.style('fill', 'none');
And am trying to update N lines with a Javascript setInterval(...) calling a method with:
graph.selectAll("path")
.data(seriesData)
.attr("transform", "translate(" + x(1) + ")")
.attr("d", line)
.transition()
.ease("linear")
.duration(transitionDelay)
.attr("transform", "translate(" + x(0) + ")");
It can draw the initial set perfectly, but as soon as I update the data array, the lines just disappear.
UPDATE 01
I realized that I am using epoch time values in the x (xAxis shows date:time) as my example would probably work if I used the illustrative seriesData above.
The problem was the "transform", "translate" using x(1), x(0) was returning huge numbers, way larger than my graph needed to be transitioned.
I modified the update N lines method (above) to use a manual approach:
New Issue:
Now the graph moves left correctly, but the lines/graph pops back to the right, each setInterval update executes.
It's push/shift'ing the seriesData array correctly but it doesn't keep scrolling to the left to show the new data that IS actually being drawn.
graph.selectAll("path")
.data(seriesData)
.attr("d", line)
.attr("transform", null)
.transition()
.ease("linear")
.duration(2000)
.attr("transform", "translate(-200)");
Another reference that I have used is this: http://bl.ocks.org/1148374
Any thoughts?

One thing that jumps out at me as a possibility for error is the data calls that are used, the initial is
.data(seriesData)
the update uses
.data([seriesData])
which may cause issues, but its hard to tell without seeing the rest of what is going on, can you perhaps put it on jsfiddle?

Related

How to make a smooth transition in a pie chart when updating values in d3?

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.

d3.js: Unusual Error

I have this d3.js project donut chart. For some reason, I am not able to access the data with in the onmousemove. The i value become zero is all the functions I pass within that event. I want to access the data of the particular slice where the mouse has moved.
How do I resolve this? Someone pls hlp!
Here is my code so far:
piesvg.selectAll("path")
.data(pie(data))
.enter().append("g")
.attr('class', 'slice')
var slice = d3.selectAll('g.slice')
.append('path')
.each(function(d) {
d.outerRadius = outerRadius - 20;
})
.attr("d", arc)
.attr('fill', function(d, i) {
return colorspie(i)
})
.on("mouseover", arcTween(outerRadius, 0))
.on("mouseout", arcTween(outerRadius - 20, 150))
.on("mousemove", function(data){
piesvg.select(".text-tooltip")
.attr("fill", function(d,i){return colorspie(i)})
.text(function(d, i){return d[i].domain + ":" + parseInt(d[i].value * 20)}); //Considers i as 0, so no matter whichever slice the mouse is on, the data of only first one is shown
});
Here is the full code:
https://jsfiddle.net/QuikProBro/xveyLfyd/1/
I dont know how to add external files in js fiddle so it doesn't work....
Here is the .tsv that is missing:
value domain
1.3038675 Cloud
2.2541437 Networking
0.15469614 Security
0.8287293 Storage
0.7292818 Analytics
0.61878455 Intelligence
1.7016574 Infra
0.4088398 Platform
Your piesvg.select is bound to be zero-indexed for i and in all probability undefined for d as it takes those values from a single tooltip element, not the slices. Hard to be 100% sure from the snippet, but I suspect you're wanting to access and use the 'data' and 'i' from the original selectAll on the slices.
.on("mousemove", function(d, i){
piesvg.select(".text-tooltip")
.attr("fill", colorspie(i))
.text(d.data.domain + ":" + parseInt(d.data.value * 20));
});
Edited as pie slices store original data in d.data property ^^^

Restart D3 bar chart animation

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);

Updating graph with new data

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();
};

Bar chart with d3.js and an associative array

I give up, I can't figure it out.
I was trying to create a bar chart with 3d.js but I can't get it working. Probably I don't understand it enough to deal with my complicate associative array.
My array has the following structure:
{"January"=>{"fail"=>13, "success"=>6},
"February"=>{"success"=>10, "fail"=>4},
"March"=>{"success"=>9, "fail"=>13},
"April"=>{"success"=>16, "fail"=>5},
"May"=>{"fail"=>52, "success"=>23},
"June"=>{"fail"=>7, "success"=>2},
"July"=>{},
"August"=>{"fail"=>6, "success"=>3},
"September"=>{"success"=>54, "fail"=>59},
"October"=>{"success"=>48, "fail"=>78},
"November"=>{"fail"=>4, "success"=>6},
"December"=>{"fail"=>1, "success"=>0}}`
I got the displaying of the axis working:
The code looks really ugly because I converted the names to a "normal" array:
monthsNames = new Array();
i = 0;
for (key in data) {
monthsNames[i] = key;
i++;
}
x.domain(monthsNames);
y.domain([0, 100]);
But I can't figure it out how to deal with the data.
I tried things like, svg.selectAll(".bar").data(d3.entries(data))
What is a good beginning I guess but I can't get the connection to the axis working.
What I want to create is a bar-chart that has the months as x-axis and every month has two bars (respectively one bar with two colours) - one for success and one for fail.
Can anybody please help me how to handle the data? Thanks in advance!
EDIT:
I cannot figure out how to scale x and y. If I use this code:
var x = d3.scale.ordinal()
.domain(monthsNames)
.range([0, width]);
var y = d3.scale.linear()
.domain([0,100])
.range([0, height]);
nothing is shown up then. If I print out the values that evaluate after using e.g. x(d.key) or x(d.value.fail) they are really strange numbers, sometimes even NaN.
EDIT:
d3.selectAll(".barsuccess")
.on('mouseover', function(d){
svg.append('text')
.attr("x", x(d.key))
.attr("y", y(d.value.success))
.text(d.value.success+"%")
.attr('class','success')
.style("font-size","0.7em")
})
.on('mouseout', function(d){
d3.selectAll(".success").remove()
});
d3.selectAll(".barfail")
.on('mouseover', function(d){
svg.append('text')
.attr("x", x(d.key)+x.rangeBand()/2)
.attr("y", y(d.value.fail))
.text(d.value.fail+"%")
.attr('class','fail')
.style("font-size","0.7em")
})
.on('mouseout', function(d){
d3.selectAll(".fail").remove()
});
Be sure to check out the bar chart tutorials here and here. You have basically all you need already. The connection between the axes and the data are the functions that map input values (e.g. "March") to output coordinates (e.g. 125). You (presumably) created these functions using d3.scale.*. Now all you need to do is use the same functions to map your data to coordinates in the SVG.
The basic structure of the code you need to add looks like
svg.selectAll(".barfail").data(d3.entries(data))
.enter().append("rect")
.attr("class", "barfail")
.attr("x", function(d) { x(d.key) })
.attr("width", 10)
.attr("y", function(d) { y(d.value.fail) })
.attr("height", function(d) { y(d.value.fail) });
and similar for success. If you use the same scale for the x axis for both types of bar, add a constant offset to one of them so the bars don't overlap. Colours etc can be set in the CSS classes.

Categories

Resources