Animating angular d3 donut on load - javascript

I have created a simple Angular/D3 donut chart.
Plunker: http://plnkr.co/edit/NyH1udkjBj3zymhGaThZ?p=preview
However i want the chart to have an animation on page load. In that, i mean, i would like the filled (blue area) to transition in.
Somethign similar to: http://codepen.io/tpalmer/pen/jqlFG/
HTML:
<div ng-app="app" ng-controller="Ctrl">
<d3-donut radius="radius" percent="percent" text="text"></d3-donut>
div>
JS:
var app = angular.module('app', []);
app.directive('d3Donut', function() {
return {
restrict: 'E',
scope: {
radius: '=',
percent: '=',
text: '=',
},
link: function(scope, element, attrs) {
var radius = scope.radius;
var percent = scope.percent;
var text = scope.text;
var svg = d3.select(element[0])
.append('svg')
.style('width', radius / 2 + 'px')
.style('height', radius / 2 + 'px');
var donutScale = d3.scale.linear().domain([0, 100]).range([0, 2 * Math.PI]);
var color = "#5599aa";
var data = [
[0, 100, "#e2e2e2"],
[0, percent, color]
];
var arc = d3.svg.arc()
.innerRadius(radius / 6)
.outerRadius(radius / 4)
.startAngle(function(d) {
return donutScale(d[0]);
})
.endAngle(function(d) {
return donutScale(d[1]);
});
svg.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", arc)
.style("fill", function(d) {
return d[2];
})
.attr("transform", "translate(" + radius / 4 + "," + radius / 4 + ")");
svg.append("text")
.attr("x", radius / 4)
.attr("y", radius / 4)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.style("fill", "#333")
.attr("text-anchor", "middle")
.text(text);
}
};
});
function Ctrl($scope) {
$scope.radius = 200;
$scope.percent = 50;
$scope.text = "40%";
}

I have combined your code with the one you cited as an example. Here is a working PLUNK.
Two things are worth noting -
1. using attrTween:
.attrTween("d", function (a) {
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
console.log(this._current);
return function(t) {
text.text( format(i2(t) / 100) );
return arc(i(t));
};
});
2. updating the data:
data = [
[0,100,"#e2e2e2"],
[0,percent,color]
];
I did some other less important changes like a more idiomatic use of the controller snippet, etc., but the above is what matters.

Would the Angular 'run' command help here?
angular.module('app', []).run(myfunction($rootScope))
See 'run' on this page https://docs.angularjs.org/api/ng/type/angular.Module
'run()' will give you one-time only execution of so-and-so a function once AngularJs has bootstrapped.

Related

How to create donut chart in d3.js?

I am trying to create responsive donut chart in d3.js.
I wrote the code for chart in d3.js, but I am not able to create according to expected chart.
Here's the actual chart, while I'm trying to achieve is this one.
My d3.js script below:
document.addEventListener('DOMContentLoaded', function(e) {
var dataset = {
oranges: [200, 200, 200, 200]
};
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var enterClockwise = {
startAngle: 0,
endAngle: 0
};
var enterAntiClockwise = {
startAngle: Math.PI * 2,
endAngle: Math.PI * 2
};
var color = d3.scale.category20();
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 20);
var svg = d3.select('#Donut-chart').append('svg')
.attr('id', 'Donut-chart-render')
.attr("width", '100%')
.attr("height", '100%')
.attr('viewBox', (-width / 2) + ' ' + (-height / 2) + ' ' + width + ' ' + height)
.attr('preserveAspectRatio', 'xMinYMin')
var path = svg.selectAll("path")
.data(pie(dataset.apples))
.enter().append("path")
.attr("fill", function (d, i) { return color(i); })
.attr("d", arc(enterClockwise))
.each(function (d) {
this._current = {
data: d.data,
value: d.value,
startAngle: enterClockwise.startAngle,
endAngle: enterClockwise.endAngle
}
});
path.transition()
.duration(750)
.attrTween("d", arcTween);
d3.selectAll("input").on("change", change);
var timeout = setTimeout(function () {
d3.select("input[value=\"oranges\"]").property("checked", true).each(change);
}, 2000);
function change() {
clearTimeout(timeout);
path = path.data(pie(dataset[this.value]));
path.enter().append("path")
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", arc(enterAntiClockwise))
.each(function (d) {
this._current = {
data: d.data,
value: d.value,
startAngle: enterAntiClockwise.startAngle,
endAngle: enterAntiClockwise.endAngle
};
}); // store the initial values
path.exit()
.transition()
.duration(750)
.attrTween('d', arcTweenOut)
.remove() // now remove the exiting arcs
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function (t) {
return arc(i(t));
};
}
function arcTweenOut(a) {
var i = d3.interpolate(this._current, { startAngle: Math.PI * 2, endAngle: Math.PI * 2, value: 0 });
this._current = i(0);
return function (t) {
return arc(i(t));
};
}
function type(d) {
d.value = +d.value;
return d;
}
});
I'm stuck with this problem, so helpful answers will be appreciated.
Thanks in advance!
To add labels to a pie chart, use arc.centroid(). You'll need an arc generator first. See this example for reference.
svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("text-anchor", "middle")
.selectAll("text")
.data(arcs)
.join("text")
.attr("transform", d => `translate(${arc.centroid(d)})`)
.call(text => text.append("tspan")
.attr("y", "-0.4em")
.attr("font-weight", "bold")
.text(d => d.data.name))
.call(text => text.filter(d => (d.endAngle - d.startAngle) > 0.25).append("tspan")
.attr("x", 0)
.attr("y", "0.7em")
.attr("fill-opacity", 0.7)
.text(d => d.data.value.toLocaleString()));

Trying to update d3.js circles with new data

I've recently began trying to teach myself D3, and I'm to get my head round the enter, update, exit paradigm.
Below I have an example of some progress circles I'm trying to work with;
http://plnkr.co/edit/OoIL8v6FemzjzoloJxtQ?p=preview
Now, as the aim here is to update the circle path without deleting them, I believe I shouldn't be using the exit function? In which case, I was under the impression that I could update my data source inside a new function and then call for the path transition, and I would get my updated value. However, this is not the case.
I was wondering if someone could help me out and show me where I'm going wrong?
var dataset = [{
"vendor-name": "HP",
"overall-score": 45
}, {
"vendor-name": "CQ",
"overall-score": 86
}];
var dataset2 = [{
"vendor-name": "HP",
"overall-score": 22
}, {
"vendor-name": "CQ",
"overall-score": 46
}];
var width = 105,
height = 105,
innerRadius = 85;
var drawArc = d3.svg.arc()
.innerRadius(innerRadius / 2)
.outerRadius(width / 2)
.startAngle(0);
var vis = d3.select("#chart").selectAll("svg")
.data(dataset)
.enter()
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
vis.append("circle")
.attr("fill", "#ffffff")
.attr("stroke", "#dfe5e6")
.attr("stroke-width", 1)
.attr('r', width / 2);
vis.append("path")
.attr("fill", "#21addd")
.attr('class', 'arc')
.each(function(d) {
d.endAngle = 0;
})
.attr('d', drawArc)
.transition()
.duration(1200)
.ease('linear')
.call(arcTween);
vis.append('text')
.text(0)
.attr("class", "perc")
.attr("text-anchor", "middle")
.attr('font-size', '36px')
.attr("y", +10)
.transition()
.duration(1200)
.tween(".percentage", function(d) {
var i = d3.interpolate(this.textContent, d['overall-score']),
prec = (d.value + "").split("."),
round = (prec.length > 1) ? Math.pow(10, prec[1].length) : 1;
return function(t) {
this.textContent = Math.round(i(t) * round) / round + "%";
};
});
function updateChart() {
vis = vis.data(dataset2)
vis.selectAll("path")
.transition()
.duration(1200)
.ease('linear')
.call(arcTween);
vis.selectAll('text')
.transition()
.duration(1200)
.tween(".percentage", function(d) {
var i = d3.interpolate(this.textContent, d['overall-score']),
prec = (d.value + "").split("."),
round = (prec.length > 1) ? Math.pow(10, prec[1].length) : 1;
return function(t) {
this.textContent = Math.round(i(t) * round) / round + "%";
};
});
}
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
var interpolate = d3.interpolate(0, 360 * (d['overall-score'] / 100) * Math.PI / 180);
return function(t) {
d.endAngle = interpolate(t)
return drawArc(d);
};
});
}
Any help/advice is much appreciated!
Thanks all
You need to refresh your data through the DOM - svg > g > path :
// SET DATA TO SVG
var svg = d3.selectAll("svg")
.data(selectedDataset)
// SET DATA TO G
var g = svg.selectAll('g')
.data(function(d){return [d];})
// SET DATA TO PATH
var path = g.selectAll('path')
.data(function(d){ return [d]; });
Storing the d3 DOM data bind object for each step you can have control of the enter(), extit(), and transition() elements. Put changing attributes of elements in the transition() function:
// PATH ENTER
path.enter()
.append("path")
.attr("fill", "#21addd")
.attr('class', 'arc')
// PATH TRANSITION
path.transition()
.duration(1200)
.ease('linear')
.attr('d', function(d){ console.log(d);drawArc(d)})
.call(arcTween);
http://plnkr.co/edit/gm2zpDdBdQZ62YHhDbLb?p=preview

D3 Progress Bar Animation Does Not Work In Angular Directive

I am having trouble getting my progress bars to animate within an AngularJS directive. I am at least able to get it to show the value that I want but I can't make it animate from 0 to an arbitrary progress value. Are there any blatant mistakes in my code that would make the animation fail? I don't understand how the animations work in D3. An additional note, there will be several progress bars on the page I am coding.
myApp.directive('progressItem', function($window){
return{
scope: '=item',
restrict: 'A',
link: function(scope, element){
var d3 = $window.d3;
var width = 120,
height = 120,
twoPi = 2 * Math.PI,
progress = parseFloat(scope.item.completed / scope.item.goals),
total = 100,
formatPercent = d3.format(".0%");
var arc = d3.svg.arc()
.startAngle(0)
.innerRadius(40)
.outerRadius(50)
;
if(scope.item.value != "add") {
var svg = d3.select(element[0]).append("svg")
.attr("width", width)
.attr("height", height)
.attr('fill', '#52AD52')
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var meter = svg.append("g")
.attr("class", "progress-meter");
meter.append("path")
.attr("class", "background")
.attr("d", arc.endAngle(twoPi));
var foreground = meter.append("path")
.attr("class", "foreground")
.attr("d", arc.endAngle(twoPi * progress));
var text = meter.append("text")
.attr("text-anchor", "middle")
.text(formatPercent(0));
var i = d3.interpolate(0, progress);
d3.transition().duration(1000).tween("progress", function () {
return function (t) {
progress = i(t);
foreground.attr("d", arc.endAngle(twoPi * progress));
text.text(formatPercent(progress));
};
});
}
else{
element.append('<img class="add" src="../images/add-user.png" />')
}
}
};
});

Angular svg or canvas to use colour gradients

I am using angular and d3 to create a donut (in a directive).
I can quite simply give the filled area a colour (in this plunker it is blue). But what i want to do is have the SVG change its colours smoothly from:
0% - 33.3% - red
33.4% - 66.66% - orange
66.7% - 100% green
Directive:
app.directive('donutDirective', function() {
return {
restrict: 'E',
scope: {
radius: '=',
percent: '=',
text: '=',
},
link: function(scope, element, attrs) {
var radius = scope.radius,
percent = scope.percent,
percentLabel = scope.text,
format = d3.format(".0%"),
progress = 0;
var svg = d3.select(element[0])
.append('svg')
.style('width', radius/2+'px')
.style('height', radius/2+'px');
var donutScale = d3.scale.linear()
.domain([0, 100])
.range([0, 2 * Math.PI]);
//var color = "#5599aa";
var color = "#018BBB";
var data = [
[0,100,"#b8b5b8"],
[0,0,color]
];
var arc = d3.svg.arc()
.innerRadius(radius/6)
.outerRadius(radius/4)
.startAngle(function(d){return donutScale(d[0]);})
.endAngle(function(d){return donutScale(d[1]);});
var text = svg.append("text")
.attr("x",radius/4)
.attr("y",radius/4)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("font-size","14px")
.style("fill","black")
.attr("text-anchor", "middle")
.text(percentLabel);
var path = svg.selectAll("path")
.data(data)
.enter()
.append("path")
.style("fill", function(d){return d[2];})
.attr("d", arc)
.each(function(d) {
this._current = d;
// console.log(this._current)
;});
// update the data!
data = [
[0,100,"#b8b5b8"],
[0,percent,color]
];
path
.data(data)
.attr("transform", "translate("+radius/4+","+radius/4+")")
.transition(200).duration(2150).ease('linear')
.attrTween("d", function (a) {
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
// console.log(this._current);
return function(t) {
text.text( format(i2(t) / 100) );
return arc(i(t));
};
});
}
};
});
Plunker: http://plnkr.co/edit/8qGMeQkmM08CZxZIVRei?p=preview
First give Id to the path like this:
var path = svg.selectAll("path")
.data(data)
.enter()
.append("path")
.style("fill", function(d){return d[2];})
.attr("d", arc)
.attr("id", function(d,i){return "id"+i;})//give id
Then inside the tween pass the condition and change the color of the path
.attrTween("d", function (a) {
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
return function(t) {
if(i2(t) < 33.3)
d3.selectAll("#id1").style("fill", "red")
else if(i2(t) < 66.6)
d3.selectAll("#id1").style("fill", "orange")
else if(i2(t) > 66.6)
d3.selectAll("#id1").style("fill", "green")
text.text( format(i2(t) / 100) );
return arc(i(t));
};
});
Working code here
EDIT
Inside your directive you can make gradient inside your defs like this:
var defs = svg.append("defs");
var gradient1 = defs.append("linearGradient").attr("id", "gradient1");
gradient1.append("stop").attr("offset", "0%").attr("stop-color", "red");
gradient1.append("stop").attr("offset", "25%").attr("stop-color", "orange");
gradient1.append("stop").attr("offset", "75%").attr("stop-color", "green");
Then in the path you can define the gradient like this:
var path = svg.selectAll("path")
.data(data)
.enter()
.append("path")
.style("fill", function(d, i) {
if (i == 0) {
return d[2];
} else {
return "url(#gradient1)";
}
})
Working code here
Hope this helps!
i want to do is have the SVG change its colours smoothly from:
0% - 33.3% - red
33.4% - 66.66% - orange
66.7% - 100% green
Assuming that you want a color transition/scale like this one:
See working code for this: http://codepen.io/anon/pen/vLVmyV
You can smothly make the color transition using a d3 linear scale like this:
//Create a color Scale to smothly change the color of the donut
var colorScale = d3.scale.linear().domain([0,33.3,66.66,100]).range(['#cc0000','#ffa500','#ffa500','#00cc00']);
Then, when you update the path (with the attrTween) to make the filling animation, take only the Path the represents the filled part of the donut, lets call it colorPath and change the fill of it adding the following like in the tween:
//Set the color to the path depending on its percentage
//using the colorScale we just created before
colorPath.style('fill',colorScale(i2(t)))
Your attrTween will look like this:
colorPath.data([[0,percent,color]])
.transition(200).duration(2150).ease('linear')
.attrTween("d", function (a) {
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
// console.log(this._current);
return function(t) {
text.text( format(i2(t) / 100) );
colorPath.style('fill',colorScale(i2(t)))
return arc(i(t));
};
});
Please note that we only update the data for the colorPath: colorPath.data([[0,percent,color]])
The whole working example is right here: http://plnkr.co/edit/ox82vGxhcaoXJpVpUel1?p=preview

How to generate multiple SVG's in a Meteor.js #each wrapper

Hi there I currently have a template helper that returns me an array with various values used to generate different rows in a table in my HTML.
<template name="stop">
{{#each thumb}}
<tr>
<td>
<h2> Do you like this product? </h2>
<h2>{{text}}</h2>
<svg id="donutChart"> </svg>
</td>
</tr>
{{/each}}
</template>
It also contains a svg tag which I also want to generate a graph for each element generated as a table row and this is what the template helper looks like.
Template.stop.helpers({
'thumb': function(data) {
var result = tweetImages.findOne();
var newResult = [];
for (var i = 0; i < result.data.length; i++) {
newResult[i] = {
data: result.data[i],
text: result.text[i]
};
}
console.log(newResult)
return newResult;
}
I'm trying to create a pie reactive pie chart for each element in the table however I don't seem to be able to access the svg in the stop template.
The d3 code works fine outside that table but cant seem to be generated for each element of the table because it can't access the svg element.
Template.donutChart.rendered = function() {
//my d3 code is here
//Width and height
var w = 300;
var h = 300;
var center = w / 2;
var outerRadius = w / 2;
var innerRadius = 0;
var radius = 150;
var arc = d3.svg.arc()
.innerRadius(40)
.outerRadius(radius + 10 - 25);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.data;
});
//Create SVG element
var svg = d3.select("#donutChart")
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + 200 + "," + 100 + ")");
// GROUP FOR CENTER TEXT
var center_group = svg.append("svg:g")
.attr("class", "ctrGroup")
.attr("transform", "translate(" + (w / 2) + "," + (h / 2) + ")");
// CENTER LABEL
var pieLabel = center_group.append("svg:text")
.attr("dy", ".35em").attr("class", "chartLabel")
.attr("text-anchor", "middle")
.text("Clothes")
.attr("fill", "white");
Deps.autorun(function() {
var modifier = {
fields: {
value: 1
}
};
Deps.autorun(function() {
var arcs = svg.selectAll("g.arc")
.data(pie(players))
var arcOutter = d3.svg.arc()
.innerRadius(outerRadius - 10)
.outerRadius(outerRadius);
var arcPhantom = d3.svg.arc()
.innerRadius(-180)
.outerRadius(outerRadius + 180);
var newGroups =
arcs
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + 150 + "," + 150 + ")")
//Set up outter arc groups
var outterArcs = svg.selectAll("g.outter-arc")
.data(pie(players))
.enter()
.append("g")
.attr("class", "outter-arc")
.attr("transform", "translate(" + 150 + ", " + 150 + ")");
//Set up phantom arc groups
var phantomArcs = svg.selectAll("g.phantom-arc")
.data(pie(players))
.enter()
.append("g")
.attr("class", "phantom-arc")
.attr("transform", "translate(" + center + ", " + center + ")");
outterArcs.append("path")
.attr("fill", function(d, i) {
return slickColor[i];
})
.attr("fill-opacity", 0.85)
.attr("d", arcOutter).style('stroke', '#0ca7d2')
.style('stroke-width', 2)
//Draw phantom arc paths
phantomArcs.append("path")
.attr("fill", 'white')
.attr("fill-opacity", 0.1)
.attr("d", arcPhantom).style('stroke', '#0ca7d2')
.style('stroke-width', 5);
//Draw arc paths
newGroups
.append("path")
.attr("fill", function(d, i) {
return slickColor[i];
})
.attr("d", arc);
//Labels
newGroups
.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
})
.style("font-size", function(d) {
return 24;
})
svg.selectAll("g.phantom-arc")
.transition()
.select('path')
.attrTween("d", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
});
arcs
.transition()
.select('path')
.attrTween("d", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
});
arcs
.transition()
.select('text')
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.text(function(d) {
return d.value;
})
.attr("fill", function(d, i) {
return textColor[i];
})
arcs
.exit()
.remove();
});
});
}
}
I can't seem to find much information on using d3.js or SVG's within a templates #each wrapper. Any help would be truly appreciated.
I would suggest wrapping your d3 code in a Deps.autorun() function as what's most likely happening is your data isn't available yet when your pie is bound to the data function and thus doesn't render anything.
Template.donutChart.rendered = function() {
Tracker.autorun(function () {
//all d3 code
});
}
You look like you're using autoruns further down but not for the bit that gets your data.

Categories

Resources