I have the following file bubbles.hbs in a ember-cli app with the following code, and I am getting the following error, Unclosed element d.y (on line 56). I tried googling the problem, but could not find a solution.
UPDATE
Here is a fiddle I made https://jsfiddle.net/395jthv9/1/ of the code below, and appears to be working.
<script type="text/javascript">
// #5b342f
var beerBackground = d3.select("body").transition()
.duration(2000)
// carter wilson color = FFE152
.style("background-color","#f5d037");
</script>
<script type="text/javascript">
w = window.innerWidth,
h = window.innerHeight;
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(d3.range(70).map(function(datum,interval) {
return {
x: interval*20,
y: 0,
// stroke-width="1",
dx: 5,
dy: -3 * (Math.random()+1),
mu: Math.random()*2
};
}))
.enter().append("svg:circle")
.attr("r", 2.5)
.attr("fill","#FFEFA0") // fill
.attr("stroke","white") // stroke
.attr("stroke-width", "1")
// .attr("opacity",".0.2")
.style("stroke-opacity", "1.0")
.style("fill-opacity", ".5");
var text = svg.append("svg:text")
.attr("x", 20)
.attr("y", 20);
var start = Date.now(),
frames = 0;
d3.timer(function()
{
// Update the circle positions.
circle
.attr("cx", function(d) {
d.x += Math.random()*3*Math.sin(Math.random()*3*d.x + Math.random()*10); if (d.x > w) d.x -= w; else if (d.x < 0) d.x += w; return d.x; })
.attr("cy", function(d) {
d.y += d.dy ;
if (d.y > h) {
d.y -= h;
}
// And the below line is giving me an error.
else if (d.y < 0) {
d.y += h;
}
return d.y;
})
.attr("r",function(d) {
return (d.y < 100) ? d3.select(this).attr("r") : d.mu*500/d.y;
}); --}}
});
</script>
You shouldn't put your JavaScript code in .hbs file using <script> tag. Move this code to JavaScript file instead.
So, move that code from bubbles.hbs to bubbles.js. You could for example execute that logic in didInsertElement hook if it's component, or after init event.
Related
I have been trying to replicate https://beta.observablehq.com/#mbostock/d3-zoomable-sunburst this in pure JS to use it in one of my projects. I am using PHP and Ajax to load Dynamic Data in JavaScript. I think the code in the Observable link is not in pure JS but rather Node or something else.
I am a newbie in Scripting, hence it is becoming very difficult for me to understand the written code. I do know that a pure JS will need the data (flare.json) in a specific format, which will generate the expected output. I can control the JSON structure from the backend, but I am unable to generate an output like the link.
I have followed multiple examples online:
https://bl.ocks.org/mbostock/4348373
And the same in d3 version 4 (which is very similar to v5, used in the Observable example):
https://bl.ocks.org/maybelinot/5552606564ef37b5de7e47ed2b7dc099
I have been trying to convert the Observable Zoomable Sunburst into JS functions, but I am unable to make it work. I have the exact same flare.json file and tried to recreate exact functions as therein Observable one. But it still is not working.
I am attaching my work. How can I get it working?
Sample Work
I have also tried to seek help on the Google Groups for d3-js, but I haven't got any help from there too.
The closest possible output which I have achieved till now is mentioned below:
var margin = {top: 288, right: 416, bottom: 288, left: 416},
radius = Math.min(margin.top, margin.right, margin.bottom, margin.left) - 5;
var hue = d3.scale.category10();
var luminance = d3.scale.sqrt()
.domain([0, 1e6])
.clamp(true)
.range([90, 20]);
var svg = d3.select("body").append("svg")
.attr("width", margin.left + margin.right)
.attr("height", margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var partition = d3.layout.partition()
.sort(function(a, b) { return d3.ascending(a.name, b.name); })
.size([2 * Math.PI, radius]);
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx ; })
.padAngle(.01)
.padRadius(radius / 3)
.innerRadius(function(d) { return radius / 3 * d.depth; })
.outerRadius(function(d) { return radius / 3 * (d.depth + 1) - 1; });
// d3.json("https://api.myjson.com/bins/byw4q", function(error, root) {
d3.json("https://gist.githubusercontent.com/mbostock/4348373/raw/85f18ac90409caa5529b32156aa6e71cf985263f/flare.json", function(error, root) {
if (error) throw error;
// Compute the initial layout on the entire tree to sum sizes.
// Also compute the full name and fill color for each node,
// and stash the children so they can be restored as we descend.
partition
.value(function(d) { return d.size; })
.nodes(root)
.forEach(function(d) {
d._children = d.children;
d.sum = d.value;
d.key = key(d);
d.fill = fill(d);
});
// Now redefine the value function to use the previously-computed sum.
partition
.children(function(d, depth) { return depth < 2 ? d._children : null; })
.value(function(d) { return d.sum; });
var center = svg.append("circle")
.attr("r", radius / 3)
.on("click", zoomOut);
center.append("title")
.text("zoom out");
var path = svg.selectAll("path")
.data(partition.nodes(root).slice(1))
.enter().append("path")
.attr("d", arc)
.style("fill", function(d) { return d.fill; })
.each(function(d) { this._current = updateArc(d); })
.on("click", zoomIn);
function zoomIn(p) {
if (p.depth > 1) p = p.parent;
if (!p.children) return;
zoom(p, p);
}
function zoomOut(p) {
if (!p.parent) return;
zoom(p.parent, p);
}
// Zoom to the specified new root.
function zoom(root, p) {
if (document.documentElement.__transition__) return;
// Rescale outside angles to match the new layout.
var enterArc,
exitArc,
outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);
function insideArc(d) {
return p.key > d.key
? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key
? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}
: {depth: 0, x: 0, dx: 2 * Math.PI};
}
function outsideArc(d) {
return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};
}
center.datum(root);
// When zooming in, arcs enter from the outside and exit to the inside.
// Entering outside arcs start from the old layout.
if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);
path = path.data(partition.nodes(root).slice(1), function(d) { return d.key; });
// When zooming out, arcs enter from the inside and exit to the outside.
// Exiting outside arcs transition to the new layout.
if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);
d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function() {
path.exit().transition()
.style("fill-opacity", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })
.attrTween("d", function(d) { return arcTween.call(this, exitArc(d)); })
.remove();
path.enter().append("path")
.style("fill-opacity", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })
.style("fill", function(d) { return d.fill; })
.on("click", zoomIn)
.each(function(d) { this._current = enterArc(d); });
path.transition()
.style("fill-opacity", 1)
.attrTween("d", function(d) { return arcTween.call(this, updateArc(d)); });
});
}
});
function key(d) {
var k = [], p = d;
while (p.depth) k.push(p.name), p = p.parent;
return k.reverse().join(".");
}
function fill(d) {
var p = d;
while (p.depth > 1) p = p.parent;
var c = d3.lab(hue(p.name));
c.l = luminance(d.sum);
return c;
}
function arcTween(b) {
var i = d3.interpolate(this._current, b);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
function updateArc(d) {
return {depth: d.depth, x: d.x, dx: d.dx};
}
d3.select(self.frameElement).style("height", margin.top + margin.bottom + "px");
<!DOCTYPE html>
<meta charset="utf-8">
<style>
circle,
path {
cursor: pointer;
}
circle {
fill: none;
pointer-events: all;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
</body>
The code written is pure javascript tough, whatever the data you are getting from Ajax the same endpoint you just need to pass here,
The example I am running here means the same should work in your project as well, Instead of calling the Ajax you can pass your Json in this line
d3.json("https://gist.githubusercontent.com/mbostock/4348373/raw/85f18ac90409caa5529b32156aa6e71cf985263f/flare.json", function(error, root)
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: #fff;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 700,
radius = (Math.min(width, height) / 2) - 10;
var formatNumber = d3.format(",d");
var x = d3.scaleLinear()
.range([0, 2 * Math.PI]);
var y = d3.scaleSqrt()
.range([0, radius]);
var color = d3.scaleOrdinal(d3.schemeCategory20);
var partition = d3.partition();
var arc = d3.arc()
.startAngle(function(d) {
return Math.max(0, Math.min(2 * Math.PI, x(d.x0)));
})
.endAngle(function(d) {
return Math.max(0, Math.min(2 * Math.PI, x(d.x1)));
})
.innerRadius(function(d) {
return Math.max(0, y(d.y0));
})
.outerRadius(function(d) {
return Math.max(0, y(d.y1));
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + (height / 2) + ")");
d3.json("https://gist.githubusercontent.com/mbostock/4348373/raw/85f18ac90409caa5529b32156aa6e71cf985263f/flare.json", function(error, root) {
if (error) throw error;
root = d3.hierarchy(root);
root.sum(function(d) {
return d.size;
});
svg.selectAll("path")
.data(partition(root).descendants())
.enter().append("path")
.attr("d", arc)
.style("fill", function(d) {
return color((d.children ? d : d.parent).data.name);
})
.on("click", click)
.append("title")
.text(function(d) {
return d.data.name + "\n" + formatNumber(d.value);
});
function labelVisible(d) {
return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03;
}
function labelTransform(d) {
const x = (d.x0 + d.x1) / 2 * 180 / Math.PI;
const y = (d.y0 + d.y1) / 2 * radius;
return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`;
}
svg.selectAll("text")
.attr("dy", "0.35em")
.attr("pointer-events", "none")
.attr("text-anchor", "middle")
.style("user-select", "none")
.attr("fill-opacity", d => +labelVisible(d.current))
.attr("transform", d => labelTransform(d.current))
.data(root.descendants().slice(1))
.enter().append("text")
.text(d => d.data.name);
});
function click(d) {
svg.transition()
.duration(750)
.tween("scale", function() {
var xd = d3.interpolate(x.domain(), [d.x0, d.x1]),
yd = d3.interpolate(y.domain(), [d.y0, 1]),
yr = d3.interpolate(y.range(), [d.y0 ? 20 : 0, radius]);
return function(t) {
x.domain(xd(t));
y.domain(yd(t)).range(yr(t));
};
})
.selectAll("path")
.attrTween("d", function(d) {
return function() {
return arc(d);
};
});
}
d3.select(self.frameElement).style("height", height + "px");
</script>
I'd like to move a selected node in a bundle layout and redraw the line.
Do you have any suggestions how I could solve that problem?
First I tried to move the node via translate:
node.attr("transform", function (nodeObject) {
var translationValue = nodeObject.y
return "rotate(" + (nodeObject.x - 90) + ")translate(" + (nodeObject.y + 20) + ")";
})
But uf course if I try to move the line that way I won't get anywhere. It will just move the whole line and I can't control the endpoints.
I've tried to remove all lines and redraw them. But the connections will point to the original point not to moved ones.
var line = d3.svg.line.radial()
.interpolate("bundle")
.tension(.75)
.radius(function (d) {
return d.y;
})
.angle(function (d) {
return d.x / 180 * Math.PI;
});
vis.selectAll("path.link").remove();
vis.selectAll("path.link")
.data(bundle(links))
.enter().append("path")
.each(function (d3Object) {
d3Object.source = d3Object[0], d3Object.target = d3Object[d3Object.length - 1];
})
.attr("d", line);
Thank you very much for your help!
You can manipulate the line attributes and redraw the line.
link.transition()
.attr("d",
function(d, i) {
if (d.target === d3Object || d.source === d3Object) {
line.radius(function (d) {
return d.y - 51;
});
line.angle(function (d) {
return d.x / 180 * Math.PI;
});
} else {
line.radius(function (d) {
return d.y;
});
line.angle(function (d) {
return d.x / 180 * Math.PI;
});
}
return line(splines[i]);
})
.duration(1500);
So I have been messing around with D3.js for a couple of days now and I have basic circle generation / animation (that act as bubbles), and I was wondering how I could animate the circles on the x axsis, so they wobble back forth as the travel / transition to the top of the page. The current animation can be viewed at chrisrjones.com/bubbles-v1.html
Demo of Solution:
Note the lack of symmetry:
http://jsfiddle.net/blakedietz/R5cRK/1/embedded/result/
Approach:
Determine a mathematical function that would properly model the movement that you want.
In this case we want a sine wave. We can modify aspects of each bubbles characteristics to give a unique movement pattern to each bubble.
Build or find a solution that utilizes the key concepts needed for this problem.
I like to search on bl.ocks.org/mbostock for examples that have the foundational parts of the problem that I'm trying to solve. On the site I found this example:http://bl.ocks.org/mbostock/1371412
Modify the given example to more similarly mirror the specified outcome.
Solution:
Here is a quick demo of a solution. I'll return to this to give you a full walk through. Modifications can be made to make the bubble placement and sizing as well as wiggle random/semi-unique per each bubble.
w = 960,
h = 500;
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(d3.range(70).map(function(datum,interval) {
return {
x: interval*20,
y: 0,
dx: 5,
dy: -3 * (Math.random()+1),
mu: Math.random()*2
};
}))
.enter().append("svg:circle")
.attr("r", 2.5)
.attr("fill","blue")
.attr("opacity",".5");
var text = svg.append("svg:text")
.attr("x", 20)
.attr("y", 20);
var start = Date.now(),
frames = 0;
d3.timer(function()
{
// Update the FPS meter.
var now = Date.now(), duration = now - start;
text.text(~~(++frames * 1000 / duration));
if (duration >= 1000) frames = 0, start = now;
// Update the circle positions.
circle
.attr("cx", function(d) { d.x += Math.random()*3*Math.sin(Math.random()*3*d.x + Math.random()*10); if (d.x > w) d.x -= w; else if (d.x < 0) d.x += w; return d.x; })
.attr("cy", function(d) { d.y += d.dy ; if (d.y > h) d.y -= h; else if (d.y < 0) d.y += h; return d.y; })
.attr("r",function(d)
{
return (d.y < 100) ? d3.select(this).attr("r") : d.mu*500/d.y;
});
});
You can do that using custom tween function for cx:
var circlesTransition = d3.selectAll("circle")
.transition()
.duration(5000)
.attr("cy", "0")
.attrTween('cx', function (d, i, a) {
return function (t) {
// Add salt, pepper and constants as per your taste
return a + (Math.random() - 0.5) * 10;
};
});
I am looking to develop a viz that consists of a node link graph. I have a series of points whose position I don't want to change unless there is a collision (one node on another) on the graph. In case of collided nodes, I want to space them so that they don't overlap. My JS code is as below
var chartWidth = 200;
var chartHeight = 200;
var widthPadding = 40;
var heightPadding = 40;
var link, node;
$(function(){
initialize();
});
function initialize() {
var jsonString = '{"nodes":[{"x":40,"y":64,"r":6,"fixed":true},{"x":40,"y":63,"r":6,"fixed":true},{"x":119,"y":53,"r":6,"fixed":true},{"x":119,"y":73,"r":6,"fixed":true},{"x":137,"y":73,"r":6,"fixed":true},{"x":140,"y":140,"r":6,"fixed":true},{"x":68,"y":57,"r":6,"fixed":true},{"x":70,"y":75,"r":6,"fixed":true},{"x":51,"y":59,"r":6,"fixed":true},{"x":51,"y":54,"r":6,"fixed":true},{"x":137,"y":40,"r":6,"fixed":true}],"links":[{"source":0,"target":1},{"source":1,"target":2},{"source":2,"target":3},{"source":3,"target":4},{"source":4,"target":5},{"source":0,"target":1},{"source":1,"target":6},{"source":6,"target":7},{"source":7,"target":4},{"source":4,"target":5},{"source":0,"target":1},{"source":1,"target":8},{"source":8,"target":9},{"source":9,"target":10},{"source":10,"target":5}]}';
drawForceDirectedNodeLink($.parseJSON(jsonString));
}
function drawForceDirectedNodeLink(graph){
var width = chartWidth + (2*widthPadding);
var height = chartHeight + (2*heightPadding);
var q = d3.geom.quadtree(graph.nodes),
i = 0,
n = graph.nodes.length;
while (++i < n) {
q.visit(collide(graph.nodes[i]));
}
var force = d3.layout.force()
.size([width, height])
.gravity(0.05)
.on("tick", function(){
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return d.r; });
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
force
.nodes(graph.nodes)
.links(graph.links)
.start();
link = link.data(graph.links)
.enter().append("line")
.attr("class", "link");
node = node.data(graph.nodes)
.enter().append("circle")
.attr("class", "node");
}
function collide(node) {
var r = node.radius + 16,
nx1 = node.x - r,
nx2 = node.x + r,
ny1 = node.y - r,
ny2 = node.y + r;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
l = (l - r) / l * .5;
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2
|| x2 < nx1
|| y1 > ny2
|| y2 < ny1;
};
}
As you can see, I have tried to implement the collision detection logic mentioned here. But some how I have not been able to get that part work.
Notice that within your jsonString declaration inside of initialize(), each node is being given an r property. However, further down within collide(), you're doing the following:
.attr("r", function(d) { return d.radius - 2; })
Make sure your nodes have a radius property attached to them. If not, the following change should do it:
.attr("r", function(d) { return d.r - 2; })
You can see on line 30 of Mike Bostock's script that his nodes are initially declared with a radius property, as opposed to your r property.
var nodes = d3.range(200).map(function() { return {radius: Math.random() * 12 + 4}; }),
UPDATE
Change node.radius to node.r and quad.point.radius to quad.point.r. And it should work. Looks like it was just a NaN problem.
I have two simple objects in d3.js, they should be circling around the center of the viewport (like planets around the sun).
I am new to d3.js and I know that I have to use transitions but as the planets have to circle all the time and not just on enter or exit I don't know where and how to set the transition.
Here is my current code:
var planets = [
{d:100,r:2},
{d:150,r:4}
];
var w = 500, h = 400, svg, circle;
function init(){
svg = d3.select("#drawArea").append("svg").attr({width: w, height: h});
var center = {
x: Math.floor(w/2),
y: Math.floor(h/2)
};
svg.append('circle').attr({
'cx': center.x,
'cy': center.y,
'r': 10,
'class': 'sun'
});
circle = svg.selectAll(".planet")
.data(planets)
.enter()
.append("circle")
.attr("class", "planet")
.attr("r", function(s){return s.r});
circle.attr({
// distance from the center
'cx': function(s){ return center.x - s.d; },
// center of the screen
'cy': function(s){ return center.y; }
});
}
And here is a jsfiddle to play around.
You need to:
Place your planets in g groups in a g that is centered on your sun
Create an d3.timer in which you rotate your group.
For, example of the use of d3.timer see Mike Bostocks Epicyclic Gearing example. Using that example, I put together something similar to what you asked: http://bl.ocks.org/4953593
Core of the example:
var w = 800, h = 800;
var t0 = Date.now();
var planets = [
{ R: 300, r: 5, speed: 5, phi0: 90},
{ R: 150, r: 10, speed: 2, phi0: 190}
];
var svg = d3.select("#planetarium").insert("svg")
.attr("width", w).attr("height", h);
svg.append("circle").attr("r", 20).attr("cx", w/2)
.attr("cy", h/2).attr("class", "sun")
var container = svg.append("g")
.attr("transform", "translate(" + w/2 + "," + h/2 + ")")
container.selectAll("g.planet").data(planets).enter().append("g")
.attr("class", "planet").each(function(d, i) {
d3.select(this).append("circle").attr("class", "orbit")
.attr("r", d.R);
d3.select(this).append("circle").attr("r", d.r).attr("cx",d.R)
.attr("cy", 0).attr("class", "planet");
});
d3.timer(function() {
var delta = (Date.now() - t0);
svg.selectAll(".planet").attr("transform", function(d) {
return "rotate(" + d.phi0 + delta * d.speed/200 + ")";
});
});
I know this might come too late. But I do hope this can help future readers if they also are facing the same problem.
I created fiddles and add some explanation in here, hope it can help:
http://www.zestyrock.com/data-visualization/d3-rotate-object-around-the-center-object-part-2/
Here is the code:
var start = Date.now();
var mode = 0;
var svg = d3.select("#canvas")
.append("svg")
.attr("width", 500)
.attr("height", 500);
svg.append("circle")
.attr("r", 50)
.attr("cx", 250)
.attr("cy", 250)
.attr("fill", "#e05038");
var rotateElements = svg.append("g");
rotateElements.append("circle")
.attr("r", 25)
.attr("cx", 250)
.attr("cy", 50)
.attr("fill", "#f2b632")
.attr("class", "orangeNode");
rotateElements.append("line")
.attr("x1", 250)
.attr("y1", 75)
.attr("x2", 250)
.attr("y2", 200)
.attr("class", "edge")
.attr("stroke", "grey");
d3.select("#start")
.on("click", startAnimation);
function startAnimation() {
if (mode === 0) {
d3.timer(function() {
var angle = (Date.now() - start);
var transform = function() {
return "rotate(" + angle + ", 250, 250)";
};
d3.selectAll(".orangeNode, .edge")
.attr("transform", transform);
if (mode === 0) {
return true;
} else {
return false;
}
});
mode = 1;
} else {
mode = 0;
}
}