How to add links to chart.js (Doughnut Charts)? - javascript

I would like to add links to doughnut charts to be able to send the user for a page with the records filtered by the clicked option.
For example here, if the user click on "Green", I want to send the user to a page that will show all "Green" records.
I didn't find a easy way to do that, and tried something like this that isn't working yet:
(I added a attribute "filter" with the "id" that I need to filter it)
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red",
filter: 1
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green",
filter: 2
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow",
filter: 3
}
]
$(document).ready(
function () {
$("#chart").click(
function(evt){
var activePoints = chart.getSegmentsAtEvent(evt);
var url = "http://example.com/?grid[f][collor][]=" + activePoints[0].filter
alert(url);
}
);
}
);
I'm not being able to get the attribute "filter" using "activePoints[0].filter"
Thank you.

Adding custom properties in JSON is a feature that may be on the roadmap for v2 (https://github.com/nnnick/Chart.js/issues/1185). As it currently stands, you can add properties in javascript doing something like this:
var segments = chart.segments;
for (var i = 0; i < segments.length; i++) {
segments[i].filter = i+1;
}
Here's a jsfiddle with the filter/id property loading in the url (http://jsfiddle.net/tcy74pcc/1/):
If you want to do this with a chart based on points rather than segments, here's a post with a similar solution for lines:
Displaying custom dataset properties in tooltip in chart.js
Hope that helps. Best of luck!

getSegmentsAtEvent is now deprecated. Use getElementsAtEvent instead.
Here's the complete function with added bonus of having dynamic colors for each segment.
var piChart = function (ctx, labelName, labels, values, filters) {
var colors = dynamicColors(values.length)
var data = {
labels: labels,
datasets: [
{
label: labelName,
backgroundColor: colors.backColors,
hoverBackgroundColor: colors.highColors,
borderColor: colors.borders,
hoverBorderColor: colors.borders,
borderWidth: 1,
data: values
}
]
};
var pieChart = new Chart(ctx, {
type: "pie",
data: data
});
if (filters != null) {
ctx.click(
function (evt) {
var activePoints = pieChart.getElementAtEvent(evt);
if (activePoints.length > 0) {
var index = activePoints[0]["_index"];
location.href = filters[index];
}
});
}
}
var dynamicColors = function (count) {
var backColors = [];
var highColors = [];
var borders = [];
for (var i = 0; i < count; i++) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var backColor = "rgba(" + r + "," + g + "," + b + ", 0.4)";
var highColor = "rgba(" + r + "," + g + "," + b + ", 0.8)";
var border = "rgba(" + r + "," + g + "," + b + ", 1)";
backColors.push(backColor);
highColors.push(highColor);
borders.push(border);
}

Related

How to access the index position i in the drag stop handler of snapsvg

I'm grouping a few elements using snapSVG's group method, pushing them to an array and applying the drag method on the array elements by looping through each element.
Could you please help me in accessing the index postion of the dragged element (grps[i]) in the drag stop handler.
g1 and var g2 are the two gropus.
grps is the array that holds the two groups.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script>
</head>
JavaScript
var s = Snap(800, 600);
var grps = [];
var objects = [];
var red = s.rect(50, 50, 200, 200).attr({
fill: "red"
});
var green = s.rect(60, 60, 100, 100).attr({
fill: "green"
});
var g1 = s.group(red, green);
grps.push(g1);
var red = s.rect(300, 50, 200, 200).attr({
fill: "red"
});
var green = s.rect(310, 60, 100, 100).attr({
fill: "green"
});
var g2 = s.group(red, green);
grps.push(g1, g2);
var drag_move = function(dx, dy) {
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
});
};
var drag_start = function() {
this.data('origTransform', this.transform().local);
};
var drag_stop = function(i) {
console.log("finished dragging");
console.log(i);
};
for (i = 0; i < grps.length; i++) {
grps[i].drag(drag_move, drag_start, drag_stop);
}
JsBin Link: http://jsbin.com/tonazosicu/10/edit?js
Thanks
You can using Function.prototype.bind() to preset some parameters like below
for (i = 0; i < grps.length; i++) {
grps[i].drag(drag_move, drag_start, drag_stop.bind(null, i));
}
Then on drag_stop you can access them like below.
var drag_stop = function(index, event) {
console.log("finished dragging");
console.log(index);
console.log(event);
};
One can achieve the same thing (in lastest versions of Snap I think) with...
grps.ForEach( function( el, i ) {
el.drag(drag_move, drag_start, drag_stop.bind(null, i))
};
But ultimately you don't need to use i, if you just use 'this' in the handler in most cases, and can simply do....
grps.ForEach( function( el ) {
el.drag(drag_move, drag_start, drag_stop)
};

ChartJS - legends and tooltips options

This is the first time I'm using ChartJS v2.
I creating a simple line chart with several datasets.
I have 3 problems:
1 - It has the correct data shown, but I have a problem with the legends, as they appear left aligned with the color box out of the canvas, and one per line like in the image bellow (https://i.stack.imgur.com/c9qBe.png).
I want the legends like float: left; in css.
2 - Other problem is the tooltips, they're very big.. like shown in the image bellow. (https://i.stack.imgur.com/txXCF.png)
I tried to find the options to achieve this but it hard for me to make it work.
3 - I want the interval in the y-axis to be 1 not 0.1.
Bellow is the JS code used to create the chart:
var scripts = $(".sending-data");
var datasets = [];
var days = [];
var counter = 0;
scripts.each(function (index, script){
var json = JSON.parse(script.innerHTML);
var data = [];
for (var i = 0; i<json.DATA.length; i++) {
data.push(json.DATA[i][2]);
if (counter === 0)
days.push(json.DATA[i][1].substr(8, 2));
}
var r = Math.floor((Math.random() * 255) + 1);
var g = Math.floor((Math.random() * 255) + 1);
var b = Math.floor((Math.random() * 255) + 1);
var rgbStr = r+ ", " +g + ", " + b;
console.log(rgbStr);
datasets.push({
label: "## " + $(script).attr("data-send-id"),
backgroundColor: 'rgba('+rgbStr+', 0.2)',
borderColor: 'rgba('+rgbStr+', 1)',
borderWidth: 2,
lineTension: 0.1,
data: data,
fill: false
});
counter++;
});
var config ={
type: 'line',
data: {
labels: days,
datasets: datasets
},
options: {
title: {
display: true,
text: 'Custom Chart Title'
},
responsive : true,
legend: {
fullWidth: false,
boxWidth: 50,
padding: 40,
position: "top",
display: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
stepSize: 1
}
}]
}
}
};
var ctx = document.querySelector("##canvas-chart").getContext("2d");
console.log(document.querySelector("##canvas-chart"));
var myLine = new Chart(ctx, config);
Dont mind the '##' selector, I'm using CFusion.
Any help from you guys?
--DISCLAIMER--
I managed to set the stepSize: 1 so the interval is 1. But still have the problem (1) and (2)
Thanks in advance!
Happy Programming!
So the problem is this - I'm dumb..
hahaha
The dataset labels had a lot of whitespace... so I just replaced all " " by "" and it showed correctly..
Thanks to all of you.
Cheers and happy programming!

How to change background color of every single bubble in highcharts?

I am trying to get user inputs and then draw a bubble chart with 100 bubbles. How can I change the background color of bubbles to different colors(up to 10 colors)?
Below is my javascript code,
<script>
function generateChart() {
var my_arr = [];
var Stakeholders = [];
$('td').each(function () {
my_arr.push($(this).children().val());
});
var length = my_arr.length;
for (var i = 0; i < length - 2; i++) {
var Stakeholder = new Object();
Stakeholder.name = my_arr[i] || 'Unknown';
Stakeholder.x = parseFloat(my_arr[i + 1] || 5);
Stakeholder.y = parseFloat(my_arr[i + 2] || 5);
Stakeholders.push(Stakeholder);
i += 2;
}
drawChart(Stakeholders);
};
function drawChart(Stakeholders) {
Highcharts.chart('container', {
chart: {
type: 'bubble',
plotBorderWidth: 1,
zoomType: 'xy',
spacingTop: 40,
spacingRight: 40,
spacingBottom: 40,
spacingLeft: 40,
borderWidth: 1
},
plotOptions: {
column: {
colorByPoint: true
}
},
series: [{
data: Stakeholders
}]
});
};
</script>
I should have added a property to Stakeholder:
var colors = ['#98d9c2', '#ffd9ce', '#db5461', '#f5853f', '#b497d6', '#dc965a', '#FF9655', '#FFF263', '#6AF9C4', "000"];
for (var i = 0; i < length - 2 ; i++) {
var Stakeholder = new Object();
var color = parseInt(Math.random() * 10);
Stakeholder.name = my_arr[i] || 'Unknown';
Stakeholder.x = parseFloat(my_arr[i + 1]);
Stakeholder.y = parseFloat(my_arr[i + 2]);
Stakeholder.z = 5;
Stakeholder.color = colors[color];
Stakeholders.push(Stakeholder);
i += 2;
}
I'm not sure if you want to assign specific colors to specific bubbles or just randomly assign colors, but you can add a color: 'somecolor' property to each bubble object in the series.
Fiddle here (see lines 96-110).
Or, you could create an array of colors, loop through your bubble series, and randomly assign a color to each bubble object.
Hope this helps.

how to change color of dots in graph using chart.js

want to change the graph dot point color
this is my js code
i had created a graph using chart.js but now i want to show different dot color in graph so that user can understand which value are more than average and which are not.
how can i achieve that i am sending you my code
var label = [];
var dataset_data = [];
$scope.number = details.number;
var total_picked = 0;
angular.forEach(details.picked_details,function(value,key)
{
label.push("Pair with "+value.paired_with);
dataset_data.push(value.no_of_times);
total_picked+=value.no_of_times;
})
var data = {
labels: label,
datasets: [{
data: dataset_data
}]
};
var ctx = document.getElementById("LineWithLine").getContext("2d");
Chart.types.Line.extend({
name: "LineWithLine",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var lines = this.options.limitLines;
for (var i = lines.length; --i >= 0;) {
var xStart = Math.round(this.scale.xScalePaddingLeft);
var linePositionY = this.scale.calculateY(lines[i].value);
//this.chart.ctx.fillStyle = lines[i].color ? lines[i].color : this.scale.textColor;
this.chart.ctx.fillStyle = "green";
this.chart.ctx.font = this.scale.font;
this.chart.ctx.textAlign = "left";
this.chart.ctx.textBaseline = "top";
if (this.scale.showLabels && lines[i].label) {
this.chart.ctx.fillText(lines[i].label, xStart + 20, linePositionY);
}
this.chart.ctx.lineWidth = this.scale.gridLineWidth;
this.chart.ctx.strokeStyle = lines[i].color ? lines[i].color : this.scale.gridLineColor;
//this.chart.ctx.strokeStyle = "green";
if (this.scale.showHorizontalLines) {
this.chart.ctx.beginPath();**strong text**
this.chart.ctx.moveTo(xStart, linePositionY);
this.chart.ctx.lineTo(this.scale.width, linePositionY);
this.chart.ctx.stroke();
this.chart.ctx.closePath();
}
this.chart.ctx.lineWidth = this.lineWidth;
this.chart.ctx.strokeStyle = this.lineColor;
//this.chart.ctx.strokeStyle = "yellow";
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(xStart - 5, linePositionY);
this.chart.ctx.lineTo(xStart, linePositionY);
this.chart.ctx.stroke();
this.chart.ctx.closePath();
}
}
});
new Chart(ctx).LineWithLine(data, {
datasetFill : false,
limitLines: [
{
value: parseInt(total_picked/47),
label: "Average Pair of "+details.number+" With Other is "+parseInt(total_picked/47),
color: '#FF0000'
}
],
});
Refer to this issue. Basically, you can create an array of colors for pointBackgroundColor.
https://github.com/chartjs/Chart.js/issues/2670

How I can have different values and different labels at graphael?

I am using a linechart at graphael. My datapoints are dates,which are not recognisable by the graphael. So I have represented every date, using 1,2,3 ....
The fact is that I need to display dates at my chart, as the x axis labels. How I can do that? I tried the label property, but it does not working.
My code is shown below:
var lines = r.linechart(30, 30, 600, 440,[[1,2,3,4,5]],[[100,150,130,85,100]], {axisxstep : 20,nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: true }).hoverColumn(function () {
this.tags = r.set();
for (var i = 0, ii = this.y.length; i < ii; i++) {
this.tags.push(r.tag(this.x, this.y[i], this.values[i], 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
}
}, function () {
this.tags && this.tags.remove();
});
Take a look at this fiddle. You have to change the attribute of each label (date for us) inside chartobject:
var lineChart = r.linechart(0, 0, 200, 250, xValues, yValues1, {
smooth: true,
colors: ['#F00', '#0F0', '#FF0'],
symbol: 'circle',
axis: '0 0 1 1'
});
for (var i = 0; i < lineChart.axis[0].text.items.length; i++) {
var label = lineChart.axis[0].text.items[i];
var originalDate = new Date(parseInt(label.attr('text'), 10));
var newText = originalDate.getDate() + "/" + (originalDate.getMonth() + 1) + "/" + (originalDate.getFullYear());
label.rotate(60);
label.attr({
'text': newText
});
}
Also, the data for graphael can only be numerical type to plot the graph, we have to create a Date object for each label in x like this:
var xValues = [
new Date("01/05/2014"),
new Date("01/06/2014"),
new Date("01/07/2014"),
new Date("01/08/2014"),
new Date("01/09/2014"),
new Date("01/10/2014"),
new Date("01/11/2014"),
new Date("01/12/2014"),
new Date("01/13/2014")
];

Categories

Resources