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

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")
];

Related

Highcharts sparklines from ajax-inserted data

You have a html table and you want to show sparkline charts from your data, exactly as in this example (from highcharts demos):
https://codepen.io/_dario/pen/rNBOGVR
Highcharts suggested code follows:
/**
* Create a constructor for sparklines that takes some sensible defaults and merges in the individual
* chart options. This function is also available from the jQuery plugin as $(element).highcharts('SparkLine').
*/
Highcharts.SparkLine = function(a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
defaultOptions = {
chart: {
renderTo: (options.chart && options.chart.renderTo) || this,
backgroundColor: null,
borderWidth: 0,
type: 'area',
margin: [2, 0, 2, 0],
width: 120,
height: 20,
style: {
overflow: 'visible'
},
// small optimalization, saves 1-2 ms each sparkline
skipClone: true
},
title: {
text: ''
},
credits: {
enabled: false
},
xAxis: {
labels: {
enabled: false
},
title: {
text: null
},
startOnTick: false,
endOnTick: false,
tickPositions: []
},
yAxis: {
endOnTick: false,
startOnTick: false,
labels: {
enabled: false
},
title: {
text: null
},
tickPositions: [0]
},
legend: {
enabled: false
},
tooltip: {
hideDelay: 0,
outside: true,
shared: true
},
plotOptions: {
series: {
animation: false,
lineWidth: 1,
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
marker: {
radius: 1,
states: {
hover: {
radius: 2
}
}
},
fillOpacity: 0.25
},
column: {
negativeColor: '#910000',
borderColor: 'silver'
}
}
};
options = Highcharts.merge(defaultOptions, options);
return hasRenderToArg ?
new Highcharts.Chart(a, options, c) :
new Highcharts.Chart(options, b);
};
var start = +new Date(),
$tds = $('td[data-sparkline]'),
fullLen = $tds.length,
n = 0;
// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
var time = +new Date(),
i,
len = $tds.length,
$td,
stringdata,
arr,
data,
chart;
for (i = 0; i < len; i += 1) {
$td = $($tds[i]);
stringdata = $td.data('sparkline');
arr = stringdata.split('; ');
data = $.map(arr[0].split(', '), parseFloat);
chart = {};
if (arr[1]) {
chart.type = arr[1];
}
$td.highcharts('SparkLine', {
series: [{
data: data,
pointStart: 1
}],
tooltip: {
headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
pointFormat: '<b>{point.y}.000</b> USD'
},
chart: chart
});
n += 1;
// If the process takes too much time, run a timeout to allow interaction with the browser
if (new Date() - time > 500) {
$tds.splice(0, i + 1);
setTimeout(doChunk, 0);
break;
}
// Print a feedback on the performance
if (n === fullLen) {
$('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
}
}
}
doChunk();
However, in my use case, the data in the table (and the data-sparkline attribute) are not hard-coded like in the example, but loaded and displayed via an AJAX call, similar to below.
//here a table row gets compiled
var tableRow = '<tr id="row_' + word.id + '">';
//this is where the sparkline data go
tableRow += '<td class="has-sparkline"></td></tr>';
//the row gets appended to tbody
$('#wordstable tbody').append(tableRow);
//finally the sparkline data are attached
//data are a simple string such as "1,2,3,4,5"
var rowId = '#row_'+word.id;
var rowIdTd = rowId + ' td.has-sparkline';
$(rowIdTd).data('sparkline',word.sparkline);
This breaks the example logic and I can't have Highcharts "see" the data.
No particular error is returned (as the data, as far as Highcharts is concerned, just isn't there, so there's nothing to do).
The doChunk bit just does all the processing in advance, and when you add your row it is no longer processing. One way of dealing with this is pulling out the part that creates a single chart into a separate function (makeChart) and when you are doing your processing you use that part directly to create your sparkline.
For example, doChunk with split out makeChart:
function makeChart(td) {
$td = td;
stringdata = $td.data('sparkline');
arr = stringdata.split('; ');
data = $.map(arr[0].split(', '), parseFloat);
chart = {};
if (arr[1]) {
chart.type = arr[1];
}
$td.highcharts('SparkLine', {
series: [{
data: data,
pointStart: 1
}],
tooltip: {
headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
pointFormat: '<b>{point.y}.000</b> USD'
},
chart: chart
});
}
// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
var time = +new Date(),
i,
len = $tds.length,
$td,
stringdata,
arr,
data,
chart;
for (i = 0; i < len; i += 1) {
makeChart($($tds[i]));
n += 1;
// If the process takes too much time, run a timeout to allow interaction with the browser
if (new Date() - time > 500) {
$tds.splice(0, i + 1);
setTimeout(doChunk, 0);
break;
}
// Print a feedback on the performance
if (n === fullLen) {
$('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
}
}
}
And then a basic example of your ajax-code:
function ajaxIsh() {
var word = {
name: 'Bird', // is the word
id: 'bird',
sparkline: '1, 2, 3, 4, 5'
};
//here a table row gets compiled
var tableRow = '<tr id="row_' + word.id + '">';
//this is where the sparkline data go
tableRow += '<th>'+word.name+'</th><td class="has-sparkline"></td></tr>';
//the row gets appended to tbody
$('#table-sparkline tbody').append(tableRow);
//finally the sparkline data are attached
//data are a simple string such as "1,2,3,4,5"
var rowId = '#row_'+word.id;
var rowIdTd = rowId + ' td.has-sparkline';
$(rowIdTd).data('sparkline',word.sparkline);
makeChart($(rowIdTd));
}
See this JSFiddle demonstration of it in action.

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 add links to chart.js (Doughnut Charts)?

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);
}

How to make consistent donut chart radius same

Following Output I am getting:
Using Charisma Library implemented my donuts chart with following code,
$(document).ready(function(){
var data = [];
var opportunities_colors = new Array();
opportunities_colors["New"] = "#999999";
opportunities_colors["Inprogress"] = "#dd5600";
opportunities_colors["Complete"] = "#73a839";
opportunities_colors["Terminate"] = "#c71c22";
opportunities_colors["Reopen"] = "#c71c22";
var opportunities_colors_option = new Array();
// alert("opportunities_colors="+opportunities_colors["New"]);
var i=0;
$("#opportunities_dropdown_id option").each(function()
{
data[i] = {};
data[i].label = $(this).text();
opportunities_colors_option.push(opportunities_colors[$(this).text()]);
data[i].data = $(this).val();
i++;
});
//donut chart
if ($("#opportunities_donutchart").length) {
$.plot($("#opportunities_donutchart"), data,
{
// colors: ["green", "red", "blue", "orange", "cyan"],
colors: opportunities_colors_option,
series: {
pie: {
innerRadius: 0.5,
show: true
}
},
legend: {
show: false
}
});
}
});
Output I am getting ,
Please help to make radius same for both charts

Categories

Resources