Draw a line after animation of each slice in a Donut - Chartistjs - javascript

I am trying to draw a "tooltip" line on completion of each slice animation using chartistjs.
Current situation
JSFiddle
Goal
I am using chartistjs library to animate the donut. I am looking for drawing line on completion of each slice (svg animate) in the chart.on('draw') function.
Looking for a line after each slice. Any recommendations?
Gist of code
var chart = new Chartist.Pie('#inner-donut', {
series: [15, 20, 30, 25],
labels: [1, 2, 3, 4]
}, {
donut: true,
showLabel: false,
width: 800,
total: 90,
height: 400,
chartPadding: 70,
plugins: [
Chartist.plugins.fillDonut({
items: [{
content: '',
offsetY : -60,
offsetX: -200
}, {
content: ''
}]
}),
]
});
chart.on('draw', function(data) {
if(data.type === 'slice') {
var pathLength = data.element._node.getTotalLength();
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 1000,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeOutQuint,
fill: 'freeze'
},
};
if(data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
data.element.animate(animationDefinition, false);
}
});

Related

Changing xaxis label from echarts library

var data = [];
var dataCount = 10;
var startTime = +new Date();
var categories = ['categoryA', 'categoryB', 'categoryC'];
var types = [
{name: 'JS Heap', color: '#7b9ce1'},
{name: 'Documents', color: '#bd6d6c'},
{name: 'Nodes', color: '#75d874'},
{name: 'Listeners', color: '#e0bc78'},
{name: 'GPU Memory', color: '#dc77dc'},
{name: 'GPU', color: '#72b362'}
];
// Generate mock data
echarts.util.each(categories, function (category, index) {
var baseTime = startTime;
for (var i = 0; i < dataCount; i++) {
var typeItem = types[Math.round(Math.random() * (types.length - 1))];
var duration = Math.round(Math.random() * 10000);
data.push({
name: typeItem.name,
value: [
index,
baseTime,
baseTime += duration,
duration
],
itemStyle: {
normal: {
color: typeItem.color
}
}
});
baseTime += Math.round(Math.random() * 2000);
}
});
function renderItem(params, api) {
var categoryIndex = api.value(0);
var start = api.coord([api.value(1), categoryIndex]);
var end = api.coord([api.value(2), categoryIndex]);
var height = api.size([0, 1])[1] * 0.6;
var rectShape = echarts.graphic.clipRectByRect({
x: start[0],
y: start[1] - height / 2,
width: end[0] - start[0],
height: height
}, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
});
return rectShape && {
type: 'rect',
shape: rectShape,
style: api.style()
};
}
option = {
tooltip: {
formatter: function (params) {
return params.marker + params.name + ': ' + params.value[3] + ' ms';
}
},
title: {
text: 'Profile',
left: 'center'
},
dataZoom: [{
type: 'slider',
filterMode: 'weakFilter',
showDataShadow: false,
top: 400,
height: 10,
borderColor: 'transparent',
backgroundColor: '#e2e2e2',
handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
handleSize: 20,
handleStyle: {
shadowBlur: 6,
shadowOffsetX: 1,
shadowOffsetY: 2,
shadowColor: '#aaa'
},
labelFormatter: ''
}, {
type: 'inside',
filterMode: 'weakFilter'
}],
grid: {
height:300
},
xAxis: {
min: startTime,
scale: true,
axisLabel: {
formatter: function (val) {
return Math.max(0, val - startTime) + ' ms';
}
}
},
yAxis: {
data: categories
},
series: [{
type: 'custom',
renderItem: renderItem,
itemStyle: {
normal: {
opacity: 0.8
}
},
encode: {
x: [1, 2],
y: 0
},
data: data
}]
};
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
First, create an array of dates like
var dates = ['2019-11-5','2019-10-3','2019-2-2','2019-1-4','2019-12-5'];
then in xAxis -> axisLabel return date
axisLabel: {
formatter: function (val,index) {
return dates[index];
}
}

Adding Labels to the Left or Right of Highcharts Funnel Visualization

My current visualization is as follows:
$(function() {
var dataEx = [
['1 Visit', 352000],
['2 Visits', 88000],
['3+ Visits', 42000]
],
len = dataEx.length,
sum = 0,
minHeight = 0.05,
data = [];
//specify your percent of prior visit value manually here:
var perc = [100, 25, 48];
for (var i = 0; i < len; i++) {
sum += dataEx[i][1];
}
for (var i = 0; i < len; i++) {
var t = dataEx[i],
r = t[1] / sum;
data[i] = {
name: t[0],
y: (r > minHeight ? t[1] : sum * minHeight),
percent: perc[i], // <----- this here is manual input
//percent: Math.round(r * 100), <--- this here is mathematical
label: t[1]
}
}
console.log(dataEx, data)
$('#container').highcharts({
chart: {
type: 'funnel',
marginRight: 100,
events: {
load: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
var bBox = p.dataLabel.getBBox()
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
},
redraw: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
}
},
},
title: {
text: 'Guest Return Funnel',
x: -50
},
tooltip: {
//enabled: false
formatter: function() {
return '<b>' + this.key +
'</b><br/>Percent of Prior Visit: '+ this.point.percent + '%<br/>Guests: ' + Highcharts.numberFormat(this.point.label, 0);
}
},
plotOptions: {
series: {
allowPointSelect: true,
borderWidth: 12,
animation: {
duration: 400
},
dataLabels: {
enabled: true,
connectorWidth: 0,
distance: 0,
formatter: function() {
var point = this.point;
console.log(point);
return '<b>' + point.name + '</b> (' + Highcharts.numberFormat(point.label, 0) + ')<br/>' + point.percent + '%';
},
minSize: '10%',
color: 'black',
softConnector: true
},
neckWidth: '30%',
neckHeight: '0%',
width: '50%',
height: '110%'
//old options are as follows:
//neckWidth: '50%',
//neckHeight: '50%',
//-- Other available options
//height: '200'
// width: pixels or percent
}
},
legend: {
enabled: false
},
series: [{
name: 'Unique users',
data: data
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 500px; height: 400px; margin: 0 auto"></div>
I would like to do the following (a photo that clarifies what I would like is HERE):
Put the category names "1 Visit", "2 Visits", "3 Visits" to the LEFT of
the funnel.
Arrange the number of guest amount and percent for each category of the
funnel so that it appears like (INSIDE the funnel):
352K 100%
Right now I have the values as the full number like 352000 but I'm
wondering if there's a way to make all numbers with 000 at the end into
a "K" at the end.
It would be great if I could also add labels for those two values AT THE
TOP of the funnel ("Guests" and "Percent of Prior Visit").
Add 2 more labels to the RIGHT of the funnel called "Q1/17 TTM" and "Avg
Value" and have values be placed for each category of the funnel
below the labels. The values for "Q1/17 TTM" should be red and the
values for "Avg Value" should be gray.
The values for "Q1/17 TTM" begin at the "2 Visits" and end at the very
bottom (under the last category)
Values for "Avg Value" begin at the first category and end at the last
category.
At the very bottom of the visualization, have a value. Don't worry about
what this is (and this is the value $12.9M in the photo).
And I want these changes to still make the data processing algorithm to visualize small values work. I would really appreciate the help! Thank you.
There isn not any option in Highcharts to handle more than one datalabels, but you can use text SVGRenderer to add additional text elements, for example:
events: {
render: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
var bBox = p.dataLabel.getBBox();
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
});
if (p.dataLabel1) {
p.dataLabel1.destroy();
p.dataLabel2.destroy();
}
p.dataLabel1 = chart.renderer.text(p.name, p.dataLabel.x - 150, p.dataLabel.y + chart.plotTop - bBox.y).add();
p.dataLabel2 = chart.renderer.text('some Text', p.dataLabel.x + 150, p.dataLabel.y + chart.plotTop - bBox.y).add();
});
}
}
Live demo: https://jsfiddle.net/BlackLabel/w2cs4ufe/1/
API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#text

Fabric.js line rendering when resizing object

Have an issue with line rendering when resizing object.
I've locked line endings positions to exact point on circles and when moving, scaling, rotating etc I have to edit lines connected to current circle.
Here is fiddle
Just try to resize circles and at some point you'll see that rendering is crashed a bit which corresponds to lines. Need a help for it, maybe rerender or something.
Or that's an issue of fabric.js
var circlesData = [{
id: 1,
x: 80,
y: 80,
r: 60
}, {
id: 2,
x: 440,
y: 190,
r: 90
}];
var connectionsData = [{
from: {id: 1, angle: 0, rdist: .8},
to: {id: 2, angle: 0, rdist: .4},
}]
var fcircles = [];
var fconnections = [];
var fcanvas;
init();
function init() {
fcanvas = new fabric.Canvas('c', {
imageSmoothingEnabled: false,
allowTouchScrolling: true,
});
fcanvas.preserveObjectStacking = true;
fcanvas.selection = false;
fcanvas.setBackgroundColor('#fff');
fcircles = circlesData.map(function(circleData) {
var circle = new fabric.Circle({
left: circleData.x,
top: circleData.y,
radius: circleData.r,
fill: 'rgba(100,100,255,0.2)',
originX: 'center',
originY: 'center'
});
circle.initialData = circleData;
circle.setControlsVisibility({
mt: false,
mb: false,
ml: false,
mr: false,
mtr: false,
});
return circle;
});
fconnections = connectionsData.map(function(connectionData) {
var line = new fabric.Line([0,0,0,0], {
strokeWidth: 6,
strokeLineCap: 'round',
fill: 'red',
stroke: 'red',
originX: 'center',
originY: 'center'
});
line.from = copyJson(connectionData.from);
line.to = copyJson(connectionData.to);
line.selectable = false;
return line;
});
fcircles.concat(fconnections).forEach(function(fobj){
fcanvas.add(fobj)
});
updateConnections(fconnections);
fcanvas.renderAll();
console.log(fcanvas.getObjects())
fcanvas.on('object:moving', onObjChange);
fcanvas.on('object:scaling', onObjChange);
fcanvas.on('object:rotating', onObjChange);
}
function onObjChange(e) {
if(['line'].indexOf(e.target.type) > -1) {
return;
}
var circle = e.target;
updateConnections(fconnections.filter(function(fconnection){
return fconnection.from.id === e.target.initialData.id || fconnection.to.id === e.target.initialData.id;
}))
}
function updateConnections(fconnections) {
fconnections.forEach(function(fconnection) {
var from = fcircles.filter(function(c){return c.initialData.id === fconnection.from.id})[0];
var to = fcircles.filter(function(c){return c.initialData.id === fconnection.to.id})[0];
var fromAngle = fconnection.from.angle - from.angle / 180 * Math.PI;
var toAngle = fconnection.to.angle - from.angle / 180 * Math.PI;
debugger;
fconnection.set({
x1: from.left + fconnection.from.rdist * from.radius * Math.cos(fromAngle),
y1: from.top + fconnection.from.rdist * from.radius * Math.sin(fromAngle),
x2: to.left + fconnection.to.rdist * to.radius * Math.cos(toAngle),
y2: to.top + fconnection.to.rdist * to.radius * Math.sin(toAngle)
});
fconnection.setCoords();
});
}
function copyJson(obj) {
return JSON.parse(JSON.stringify(obj));
}
Add to your Line object property:
objectCaching: false
From fabricjs documentation:
objectCaching :Boolean When true, object is cached on an additional
canvas. default to true since 1.7.0

Total of values in HighCharts Pie Chart

Is there a way to get a grand total of values in legend or any other place in pie charts?
Here is the code with legend ,but instead of adding the total of percentage,i want to display the total of values..
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
width: 500,
borderWidth: 2
},
title: {
text: 'demo'
},
credits: {
enabled: false
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 30,
labelFormat: '{name} ({percentage:.1f}%)',
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '12px'
}
}
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.percentage, 2) + '%<br />' + '<b>' + this.point.name + '</b><br />Rs.: ' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
data: (function () {
var names = 'Ari,Bjartur,Bogi,Bragi,Dánjal,Dávur,Eli,Emil,Fróði,Hákun,Hanus,Hjalti,Ísakur,' +
'Johan,Jóhan,Julian,Kristian,Leon,Levi,Magnus,Martin,Mattias,Mikkjal,Nóa,Óli,Pauli,Petur,Rói,Sveinur,Teitur',
arr = [];
Highcharts.each(names.split(','), function (name) {
arr.push({
name: name,
y: Math.round(Math.random() * 100)
});
});
return arr;
}()),
showInLegend: true
}]
});
});
I would use the Renderer.text to annotate the chart (and not do it in the legend since you have so many data points).
chart: {
events: {
load: function(event) {
var total = 0; // get total of data
for (var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},
Fiddle example.
In addition to Mark's answer, to calculate the total, we do not need the for-loop statement. So, the code can be reduced.
chart: {
events: {
load: function(event) {
var total = this.series[0].data[0].total;
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},

Snap SVG masking not working properly in Chrome 34

I am testing Snap SVG and it's pretty nice SVG library, but I cannot get it to work in Chrome, but it's working ok in Safari, Firefox and Opera. You can see it here.
Here is the JS files that generates the SV
(function () {
var s = Snap('#snap'),
grid = 160,
imgSize = 130,
outerSize = 100,
innerSize = 90;
var team = {
person1: {
img: 'person1_bnw.jpg',
color: 'person1_color.jpg',
x: grid,
y: 0
},
person2: {
img: 'person2_bnw.jpg',
color: 'person2_color.jpg',
x: grid*2,
y: 0
}
// I removed rest of the members, but this is the idea
};
for (member in team) {
createMember(team[member]);
}
function createMember(member) {
var img, outer, mask, bnw, color, colorMask;
var showMatrix = new Snap.Matrix();
showMatrix.scale(1, 1, member.x + 130 /2, member.y + 130 /2);
var hideMatrix = new Snap.Matrix();
hideMatrix.scale(2, 2, member.x + 130 /2, member.y + 130 /2);
img = s.image('img/' + member.img, member.x, member.y, imgSize, imgSize);
mask = s.rect(member.x + 20, member.y + 20, innerSize, innerSize)
.transform('r-45')
.attr({ fill: '#fff' });
img.attr({ mask: mask });
if (member.color) {
color = s.image('img/' + member.color, member.x, member.y, imgSize, imgSize);
colorMask = s.rect(member.x + 20, member.y + 20, innerSize, innerSize)
.transform('r-45')
.attr({ fill: '#fff' });
color.attr({ mask: colorMask, transform: 's0', opacity: 0 });
}
outer = s.rect(member.x + 15, member.y + 15, outerSize, outerSize)
.transform('r-45')
.attr({
'fill-opacity': 0,
'stroke-width': 2,
'stroke-opacity': 0.5,
'stroke': '#000'
});
if (member.color) {
outer.mouseover(function () {
img.animate({ transform: hideMatrix, opacity: 0 }, 200, mina.bounce, function () { img.attr({ transform: 's0' }) });
color.animate({ transform: showMatrix, opacity: 1 }, 200, mina.bounce);
});
outer.mouseout(function () {
img.animate({ transform: showMatrix, opacity: 1 }, 200, mina.bounce);
color.animate({ transform: hideMatrix, opacity: 0 }, 200, mina.bounce, function () { color.attr({ transform: 's0' }) });
});
}
}
})();
You can check out the GitHub repo as well: https://github.com/mupkoo/snap-team

Categories

Resources