Improving D3 Sequence sunburst to have zooming technique - d3.js

I have a normal sequence sunburst jsfiddle as you can it is working normally.
I am trying to improve this sunburst to get a zooming technique.
with the following code I can et one step zooming,
var path = vis.data([json]).selectAll("path")
.
.
.on("click", click)
.each(stash);
the click function is:
function click(d)
also the code has the arctween, stash and reposition functions as below
function arcTween(a){
var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
return function(t) {
var b = i(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
};
}
function stash(d) {
d.x0 =0;// d.x;
d.dx0 =0;// d.dx;
}
function reposition(node, x, k) {
node.x = x;
if (node.children && (n = node.children.length)) {
var i = -1, n;
while (++i < n) x += reposition(node.children[i], x, k);
}
return node.dx = node.value * k;
}
this is the final version of my sunburst with zooming JSfiddle
the Question is: How can I make the sequences sunburst works with zooming approach?
and how to stop zoomin and o back as [bilevel or zoomable sunburst]

Related

Y axis line is flickering using D3

I'm trying to create a running line chart where it animates changes and the X and Y axis and the line itself.
I've started with the basic animation explanation at:
https://observablehq.com/#d3/learn-d3-animation?collection=#d3/learn-d3
And created my own (see code and link below)
My problem is that as soon as I add the await chartBug.update the Y axis starts flickering.
See animated gif below:
I think I need the await, to wait for the animation to complete before I start the next animation, and control the smooth speed of the animation.
While I'm here I would like also to ask how can I force the axis to draw the start and end ticks.
Thanks for the help
Here's a link to the page on www.observablehq.com
Here's the Animated gif of the problem - the source code is below:
chartBug = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const zx = x.copy(); // x, but with a new domain.
const zy = y.copy(); // x, but with a new domain.
const line = d3
.line()
.x(d => zx(d.date))
.y(d => y(d.close));
const path = svg
.append("path")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("stroke-miterlimit", 1)
.attr("d", line(data));
const gx = svg.append("g").call(xAxis, zx);
const gy = svg.append("g").call(yAxis, y);
return Object.assign(svg.node(), {
update(step) {
const partialData = [];
for (let i = 0; i < step; i++) {
partialData.push(data[i]);
}
const t = svg.transition().duration(50);
zx.domain(d3.extent(partialData, d => d.date));
gx.transition(t).call(xAxis, zx);
zy.domain([0, d3.max(partialData, d => d.close)]);
gy.transition(t).call(yAxis, zy);
path.transition(t).attr("d", line(data));
return t.end();
}
});
}
{
replay2;
for (let i = 0, n = data.length; i < n; ++i) {
await chartBug.update(i);
yield i;
}
}
the issue seems to be on your yAxis function, every new update and rescale yAxis is recreated and the domain is redraw and removed, if you don't mind keep it you can remove call(g => g.select(".domain").remove() from it.
You need to await to update after the transition is done. I think this also answer your other question
yAxis = (g, scale = y) => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(scale).ticks(height / 40))

D3.js attr in json not working? [duplicate]

I've been trying to convert a nice D3 chart example ( https://jsfiddle.net/thudfactor/HdwTH/ ) to an Angular2 component with the new D3 v4.
I do however get a "cannot read property text of null" exception with the following code:
var textLabels = labelGroups.append("text").attr({
x: function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var x = Math.cos(midAngle) * cDim.labelRadius;
var sign = (x > 0) ? 1 : -1
var labelX = x + (5 * sign)
return labelX;
},
y: function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var y = Math.sin(midAngle) * cDim.labelRadius;
return y;
},
'text-anchor': function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var x = Math.cos(midAngle) * cDim.labelRadius;
return (x > 0) ? "start" : "end";
},
'class': 'label-text'
}).text(function (d, i) { <--------------- exception
return d.data.label;
});
labelgroups is a selection, append should work, so it must be the .attr({}) causing the problem. It does however work fine in the jsfiddle.
Has this syntax changed in D3 v4? How would it be correct?
New answer
Because d3-selection-multi has been deprecated, the adequate solution is just using the regular attr method:
selection.attr("foo", foo)
.attr("bar", bar)
etc...
Previous answer
From D3 v4 onwards you cannot use objects to set attr or style anymore. To do so, you have to reference the mini library D3-selection-multi:
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
After doing that, change your code from attr to attrs (yes, like a plural):
var textLabels = labelGroups.append("text").attrs({
//mind the 's' here-------------------------ˆ
});
Do the same for the styles: it should be styles, as a plural, not style.
If you don't want to change all this, simply do as the "regular" way: set x, y, text-anchor and class in separate attr.
Here is the selection-multi documentation: https://github.com/d3/d3-selection-multi/blob/master/README.md#selection_attrs

d3 v4 voronoi find nearest neighbours in a scatterplot svg filled with (dots / circles)

I am trying to find the nearest neighbors in a scatterplot using the data attached below, with the help of this snippet -
const voronoiDiagram = d3.voronoi()
.x(d => d.x)
.y(d => d.y)(data);
data.forEach(function(d){
console.log(d, voronoiDiagram.find(d.x, d.y, 50));
});
Now the dataset I am using is the standard iris sepal, petal lengths data in
format -
{"sepalLength":7.7,"sepalWidth":3,"petalLength":"6.1","petalWidth":"2.3","species":"virginica","index":135,"x":374.99999999999994,"y":33.75,"vy":0,"vx":0},
{"sepalLength":6.3,"sepalWidth":3.4,"petalLength":"5.6","petalWidth":"2.4","species":"virginica","index":136,"x":524.9999999999999,"y":191.25,"vy":0,"vx":0},
{"sepalLength":6.4,"sepalWidth":3.1,"petalLength":"5.5","petalWidth":"1.8","species":"virginica","index":137,"x":412.5,"y":179.99999999999994,"vy":0,"vx":0},
{"sepalLength":6,"sepalWidth":3,"petalLength":"4.8","petalWidth":"1.8","species":"virginica","index":138,"x":374.99999999999994,"y":225,"vy":0,"vx":0},
....
So, essentially it is in the form of
{d: {x, y, sepal length, width, petal length, width}.
Now, I am trying to find the nearest neighbors with d3 voronoi from reference.
But, all I get is this in results -
Let point d in my dataset =
{"sepalLength":5.9,"sepalWidth":3,"petalLength":"5.1","petalWidth":"1.8","species":"virginica","index":149,"x":374.99999999999994,"y":236.24999999999997,"vy":0,"vx":0}
Now, the voronoiDiagram.find(d.x, d.y, 50) for this is resulting in -
"[375,236.25]"
That is, the same point with coordinates rounded off instead of another point.
So, how do I exclude current point being scanned in this case from the voronoi diagram.
Also, If I exclude that point & re-calculate everything would this be good from the performance perspective ?
Can anyone help me with finding nearest neighbors from a set of points
with d3 voronoi / quadtrees (I have tried a couple of examples already from Mike Bostock but couldn't get them to work in my case because of some errors,
so will post them if d3 voronoi does not help).
voronoiDiagram.find(y, x, r) will only ever return, at most, once cell. From the API documentation:
Returns the nearest site to point [x, y]. If radius is specified, only sites within radius distance are considered. (link)
I've previously read that as being plural, apparently I've never looked closely (and I think there is a large amount of utility in being able to find all points within a given radius).
What we can do instead is create a function fairly easily that will:
start with voronoiDiagram.find() to find the cell the point falls in
find the neighbors of the found cell
for each neighbor, see if its point is within the specified radius
if a neighbors point is within the specified radius:
add the neighbor to a list of cells with points within the specified radius,
use the neighbor to repeat steps 2 through 4
stop when no more neighbors have been found within the specified radius, (keep a list of already checked cells to ensure none are checked twice).
The snippet below uses the above process (in the function findAll(x,y,r)) to show points within the specified distance as orange, the closest point will be red (I've set the function to differentiate between the two).
var width = 500;
var height = 300;
var data = d3.range(200).map(function(d) {
var x = Math.random()*width;
var y = Math.random()*height;
var index = d;
return {x:x,y:y,index:index}
});
var svg = d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height);
var circles = svg.selectAll()
.data(data, function(d,i) { return d.index; });
circles = circles.enter()
.append("circle")
.attr("cx",function(d) { return d.x; })
.attr("cy",function(d) { return d.y; })
.attr("r",3)
.attr("fill","steelblue")
.merge(circles);
var voronoi = d3.voronoi()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.size([width,height])(data);
var results = findAll(width/2,height/2,30);
circles.data(results.nearest,function(d) { return d.index; })
.attr("fill","orange");
circles.data([results.center],function(d) { return d.index; })
.attr("fill","crimson");
var circle = svg.append("circle")
.attr("cx",width/2)
.attr("cy",height/2)
.attr("r",30)
.attr("fill","none")
.attr("stroke","black")
.attr("stroke-width",1);
circle.transition()
.attrTween("r", function() {
var node = this;
return function(t) {
var r = d3.interpolate(30,148)(t);
var results = findAll(width/2,height/2,r);
circles.data(results.nearest,function(d) { return d.index; })
.attr("fill","orange");
return r;
}
})
.duration(2000)
.delay(1000);
function findAll(x,y,r) {
var start = voronoi.find(x,y,r);
if(!start) return {center:[],nearest:[]} ; // no results.
var queue = [start];
var checked = [];
var results = [];
for(i = 0; i < queue.length; i++) {
checked.push(queue[i].index); // don't check cells twice
var edges = voronoi.cells[queue[i].index].halfedges;
// use edges to find neighbors
var neighbors = edges.map(function(e) {
if(voronoi.edges[e].left == queue[i]) return voronoi.edges[e].right;
else return voronoi.edges[e].left;
})
// for each neighbor, see if its point is within the radius:
neighbors.forEach(function(n) {
if (n && checked.indexOf(n.index) == -1) {
var dx = n[0] - x;
var dy = n[1] - y;
var d = Math.sqrt(dx*dx+dy*dy);
if(d>r) checked.push(n.index) // don't check cells twice
else {
queue.push(n); // add to queue
results.push(n); // add to results
}
}
})
}
// center: the point/cell that is closest/overlapping, and within the specified radius, of point x,y
// nearest: all other cells within the specified radius of point x,y
return {center:start,nearest:results};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

Keep changed position of NVD3 legend after click

I am trying to change nvd3 chart legend position to the bottom of the chart.
I've heard about the:
d3.select(.nv-legendWrap).attr("transform", "translate(x, y)")
It's actually working but a click action on the legend will replace it at the top of the chart.
And I don't get how to use de legendPostion function (that is not a function according to the console).
After doing this (mind the quotes):
d3.select(".nv-legendWrap").attr("transform", "translate(x,y)")
Which will, as you know, move the legend to another position, set the same position when you click it:
d3.select(".nv-legendWrap").on("click", function(){
d3.select(this).attr("transform", "translate(x,y)");
})
Here is an example, the original position of the legend is on the top, but I'm moving it to the bottom. Click it and it will remain in the same position:
var data = function() {
return stream_layers(3,10+Math.random()*100,.1).map(function(data, i) {
return {
key: 'Stream' + i,
values: data
};
});
}
/* Inspired by Lee Byron's test data generator. */
function stream_layers(n, m, o) {
if (arguments.length < 3) o = 0;
function bump(a) {
var x = 1 / (.1 + Math.random()),
y = 2 * Math.random() - .5,
z = 10 / (.1 + Math.random());
for (var i = 0; i < m; i++) {
var w = (i / m - y) * z;
a[i] += x * Math.exp(-w * w);
}
}
return d3.range(n).map(function() {
var a = [], i;
for (i = 0; i < m; i++) a[i] = o + o * Math.random();
for (i = 0; i < 5; i++) bump(a);
return a.map(stream_index);
});
}
/* Another layer generator using gamma distributions. */
function stream_waves(n, m) {
return d3.range(n).map(function(i) {
return d3.range(m).map(function(j) {
var x = 20 * j / m - i / 3;
return 2 * x * Math.exp(-.5 * x);
}).map(stream_index);
});
}
function stream_index(d, i) {
return {x: i, y: Math.max(0, d)};
}
nv.addGraph(function() {
var chart = nv.models.multiBarChart();
chart.xAxis
.tickFormat(d3.format(',f'));
chart.yAxis
.tickFormat(d3.format(',.1f'));
chart.multibar.stacked(true); // default to stacked
chart.showControls(false); // don't show controls
d3.select('#chart svg')
.datum(data())
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
d3.select(".nv-legendWrap").attr("transform", "translate(0,340)");
d3.select(".nv-legendWrap").on("click", function(){
d3.select(this).attr("transform", "translate(0,340)");
})
return chart;
});
#chart svg {
height: 400px;
width: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.min.js"></script>
<div id="chart">
<svg></svg>
</div>
Have in mind that the legendPosition method is quite limited, you can only choose top or right:
chart.legendPosition("top")
chart.legendPosition("right")

Can't add class through .attr method [duplicate]

I've been trying to convert a nice D3 chart example ( https://jsfiddle.net/thudfactor/HdwTH/ ) to an Angular2 component with the new D3 v4.
I do however get a "cannot read property text of null" exception with the following code:
var textLabels = labelGroups.append("text").attr({
x: function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var x = Math.cos(midAngle) * cDim.labelRadius;
var sign = (x > 0) ? 1 : -1
var labelX = x + (5 * sign)
return labelX;
},
y: function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var y = Math.sin(midAngle) * cDim.labelRadius;
return y;
},
'text-anchor': function (d, i) {
var centroid = pied_arc.centroid(d);
var midAngle = Math.atan2(centroid[1], centroid[0]);
var x = Math.cos(midAngle) * cDim.labelRadius;
return (x > 0) ? "start" : "end";
},
'class': 'label-text'
}).text(function (d, i) { <--------------- exception
return d.data.label;
});
labelgroups is a selection, append should work, so it must be the .attr({}) causing the problem. It does however work fine in the jsfiddle.
Has this syntax changed in D3 v4? How would it be correct?
New answer
Because d3-selection-multi has been deprecated, the adequate solution is just using the regular attr method:
selection.attr("foo", foo)
.attr("bar", bar)
etc...
Previous answer
From D3 v4 onwards you cannot use objects to set attr or style anymore. To do so, you have to reference the mini library D3-selection-multi:
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
After doing that, change your code from attr to attrs (yes, like a plural):
var textLabels = labelGroups.append("text").attrs({
//mind the 's' here-------------------------ˆ
});
Do the same for the styles: it should be styles, as a plural, not style.
If you don't want to change all this, simply do as the "regular" way: set x, y, text-anchor and class in separate attr.
Here is the selection-multi documentation: https://github.com/d3/d3-selection-multi/blob/master/README.md#selection_attrs

Resources