How to get Piwik Json Data and use it with chart.js? - json

I use the piwik php api to generate data like this:
[
{"label":"1680x1050","nb_visits":9,"nb_actions":53,"max_actions":27,"sum_visit_length":3051,"bounce_count":3,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":7,"sum_daily_nb_users":0,"segment":"resolution==1680x1050"},
{"label":"1440x900","nb_visits":1,"nb_actions":1,"max_actions":1,"sum_visit_length":0,"bounce_count":1,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":1,"sum_daily_nb_users":0,"segment":"resolution==1440x900"}
]
and i want to use chart.js to visualize this data, at the moment my code looks like this and doesn't work:
var chartjsData = [];
var chartjsLabel = [];
$.getJSON("piwik.php", function (json) {
///src = http://stackoverflow.com/questions/24696329/how-to-use-json-data-in-chart-js
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].nb_visits);
chartjsLabel.push(json[i].label);
}
});
var barChartData = {
labels :[chartjsLabel],datasets : [
{
fillColor : "rgba(220,280,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : chartjsData
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: barChartData,
});
can maybe someone give me a working example how to work with chart.js and piwik's json data, or a hint how to get this working, thanks alot!

I got it like this:
var label = [];
var data = [];
$.getJSON("piwik.php", function (json) {
for (var i = 0; i < json.length; i++) {
label.push(json[i].label);
data.push(json[i].nb_visits);
}
graph();
});
function graph(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
}
});
};

Related

HOW to use JSON file in chart js?

I want to add data from json file to chart js in (django) but it do not appear
in our file placed in static folder
<canvas id="canvas" width="80" height="30"></canvas>
$.getJSON("JSONnigberOfPopulition.json", function (json) {
var labelsChart = json.map(function(item) {
return item.AvgTravelTime;
});
var dataChart = json.map(function(item) {
return item.Pop_ofNeigbor_riyadh;
});
Here as you can see this chart part :
var ctx = canvas.getContext('2d');
var config = {
type: 'line',
data: {
labels:labelsChart,
datasets:[{
label: 'Graph Line',
data: dataChart,
backgroundColor:'rgba(0, 119, 204, 0.3)'
}]
}
};
var myChart = new Chart(ctx,config);
});

Adding images to google visualization chart

How can i add images in google visualization chart.
Below is the script which i am trying
google.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('example4.2');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'President', 'George Washington', new Date(0,0,0,12,0,0), new Date(0,0,0,12,3,0) ],
[ 'President', '<img class="devsite-avatar" src="http://i.stack.imgur.com/FVDLV.jpg?s=32&g=1">John Adams', new Date(0,0,0,12,3,3), new Date(0,0,0,12,14,0) ],
[ 'President', 'Thomas Jefferson', new Date(0,0,0,12,15,1), new Date(0,0,0,12,28,0) ],
[ 'President', '', new Date(0,0,0,13,0, 0), new Date(0,0,0,13,0,0) ]
]);
var options = {
timeline: { groupByRowLabel: true },
allowHTML: true,
avoidOverlappingGridLines: false
};
chart.draw(dataTable, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
'version':'1','packages':['timeline']}]}"></script>
<div id="example4.2" style="height: 200px;"></div>
Please help me to understand what I am missing here.
It seems that allowHTML option is not supported for google.visualization.Timeline object, but you could consider to customize SVG (insert image into bar in this example) once the chart is rendered as demonstrated below:
google.load('visualization', '1.0', {
'packages': ['timeline','annotatedtimeline']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('example4.2');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['President', 'George Washington', new Date(1789, 3, 30), new Date(1797, 2, 4)],
['President', 'John Adams', new Date(1797, 2, 4), new Date(1801, 2, 4)],
['President', 'Thomas Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4)]]);
var options = {
timeline: { groupByRowLabel: false}
};
chart.draw(dataTable, options);
configureChart();
}
function configureChart() {
var chartContainer = document.getElementById('example4.2');
var svg = chartContainer.getElementsByTagName('svg')[0];
var barLabels = svg.querySelectorAll("text[text-anchor='start']");
for (var i = 0; i < barLabels.length; i++) {
if (barLabels[i].innerHTML == "George Washington") {
var barArea = barLabels[i].previousSibling;
var x = barArea.getAttribute('x');
var y = barArea.getAttribute('y');
var presidentIcon = createImage({ href: 'https://upload.wikimedia.org/wikipedia/commons/e/e4/Lawrence_Washington.jpg', x: x, y: y, width: 20, height: 20 });
barArea.parentElement.appendChild(presidentIcon);
barLabels[i].setAttribute('x', parseFloat(x) + 20);
}
}
}
function createImage(options) {
var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttributeNS(null, 'height', options.height);
image.setAttributeNS(null, 'width', options.width);
image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', options.href);
image.setAttributeNS(null, 'x', options.x);
image.setAttributeNS(null, 'y', options.y);
image.setAttributeNS(null, 'visibility', 'visible');
return image;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="example4.2" style="height: 600px;"></div>

Highcharts and JSON parameters

My file data.json is :
[{"metier":"Administratif","total":197555},
{"metier":"Canalisateur","total":4717},
{"metier":"Carreleur","total":15513}]
Please let me know how can i write my javascript code ?
I would like to create a chart with column ("metier" is X and "total" is Y)
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Thanks in Advance..
See the example of parser:
var output = [];
$.each(data,function(i,d){
output.push({
name: d.metier,
y: d.total
});
});
This code needs to be run in $.getJSON() callback body.
http://jsfiddle.net/sbochan/g7uzzyka/1/

Select which columns from CSV to graph with HighChart

As I was looking at the question How do I select which columns from my CSV to chart with HighChart? I tried to apply it using a csv file but I could not get it to work!
What am I doing wrong? Thank you in advance:
$(function () {
//var data = "Year,Month,Day,Hour,Time,kWh,Savings,Total kWh\n2013,02,06,11,11:00,0,0,308135\n2013,02,06,11,11:59,15,1.875,308150\n2013,02,06,12,12:59,27,3.375,308177\n2013,02,06,13,13:59,34,4.25,308211\n2013,02,06,14,14:59,32,4,308243";
var options = {
chart: {
renderTo: 'EXAMPLE',
defaultSeriesType: 'line'
},
title: {
text: 'Current Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: hassayampa.csv',
x: -20
},
xAxis: {
type: 'datetime'
},
yAxis:{
title: {
text: 'Temperature (\xB0C)'
},
//min: 0
},
legend:{
layout: 'vertical',
//backgroundColor: '#FFFFFF',
//floating: true,
align: 'left',
//x: 100,
verticalAlign: 'top',
//y: 70,
borderWidth: 0
},
series: [{
name: 'PRIM OUT TEMP',
data: []
}, {
name: 'SEC OUT TEMP',
data: []
}]
};
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
});
new Highcharts.Chart(options);
});
Here is the jsfiddle:http://jsfiddle.net/tonystinge/3bQne/1223/
I got it now...
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
// parsing here...
});
new Highcharts.Chart(options);
});
Your problem is the placement of the new Highcharts.Chart(options) call. $.get (like most ajax calls) is asynchronous So the new Highcharts will be called before it completes.
Change it to this:
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
new Highcharts.Chart(options); // this is now in the $.get callback function
});

Can't display axis to my rickshaw chart

I'm trying to display x- and y-axis to my charts.
I'm using JSON for the data.
This is my following code :
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 580,
height: 300,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) {
return d },
onComplete: function(transport) {
var graph = transport.graph;
var hoverDetail = new Rickshaw.Graph.HoverDetail( {
graph: graph
} );
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle( {
graph: graph,
legend: legend
} );
},
series: [
{
name: 'ligne1',
color: '#c05020',
}, {
name: 'ligne2',
color: '#30c020',
}, {
name: 'ligne3',
color: '#6060c0'
}, {
name: 'ligne4',
color: 'red'
}
],
onComplete: function() {
var x_axis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
x_axis.graph.update();
}
}
);
Can anyone help me and tell me how to do it ?
I have numbers as x- and y-datas (not words)
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 580,
height: 300,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) { d[0].data[0].y = 80; return d },
onComplete: function(transport) {
// important . do not forget
var graph = transport.graph;
var detail = new Rickshaw.Graph.HoverDetail({ graph: graph });
var legend = new Rickshaw.Graph.Legend({graph: graph,element: document.querySelector('#legend')});
var xAxis = new Rickshaw.Graph.Axis.Time({graph: graph});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({graph: graph});
yAxis.render();
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
},
series: [
{
name: 'ligne1',
color: '#c05020',
}, {
name: 'ligne2',
color: '#30c020',
}, {
name: 'ligne3',
color: '#6060c0'
}, {
name: 'ligne4',
color: 'red'
}
],
});
Changing Rickshaw.Graph.Axis.Time to Rickshaw.Graph.Axis.X worked for me in a very similar situation. BTW your example code shows two definitions of onComplete, which I assume isn't intended?