I have been customizing the following jsfiddle in order to display data from a database. http://jsfiddle.net/jlbriggs/7ntyzo6u/
I am using JSON in order to retrieve data in my database. In the jsfiddle, there are 3 charts which can be switched between by clicking buttons. But when you load the page, chart1 is the default chart showing. Now I have edited chart1 so that it will display my database data:
var chart,
chartOptions = {},
chartData = {};
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
var tableName = '<?php echo $tableName; ?>'
$.getJSON("../../companies/charts/Data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
});
My problem is, that the chart shows up as empty after loading the page. Only when I click the chart1 button will the data show up. Can anyone tell me if this is because I am missing something after setting the xAxis and series data in the above code?
Since $.getJSON is asynchronous (see comment below) I have tried to now send the request using ajax instead. Below is my attempt, but this is flawed since the chart will now not even display data upon clicking the 'chart1' button. The chart does come up, but is empty:
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
var tableName = '<?php echo $tableName; ?>'
$.ajax({
url: "../../companies/charts/Data.php",
data: {id: escape(tableName)},
dataType: "json",
async: false,
succes: function(data) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
}
});
Thanks in advance for your assistance!
My assumption is that since $.getJSON is asynchronous , the chart is already loaded before the data is populated.
You can try calling the setData method on the series inside the $.getJSON block.This will force a chart redraw :
chartOptions.chart1.series[0].setData(json[6]['data'],true);
Or try to send the request using $.ajax with async:false.Replace the following block with the $.getJSON block.
$.ajax({
url: "../../companies/charts/Data.php",
data: {id: escape(tableName)},
async:false
}).done(function() {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
});
I think this should get you going.
Read more about it over here: jQuery.ajax
Related
I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});
I am trying to update the series data option for 'pie' type chart:
I am using exporting buttons to display options to change chart type, all other chart types work well except pie which needs a different format of series data.
exporting: {
buttons: {
lineButton: {
text: 'line',
onclick: function () {
for(i=0;i<this.series.length;i++) {
this.series[i].update({
type: "line"
});
}
}
},
barButton: {
text: 'bar',
onclick: function () {
for(i=0;i<this.series.length;i++) {
this.series[i].update({
type: "column"
});
}
}
},
pieButton: {
text: 'pie',
onclick: function () {
var pieSeries = [];
$.each(category_totals, function(j, k) {
pieSeries.push( { name: j , y: k } );
});
for(i=0;i<this.series.length;i++) {
this.series[i].remove();
}
this.series = [{
name: title,
colorByPoint: true,
data: pieSeries
}];
this.series[0].update({
type: "pie"
});
}
}
}
...
And I get this error: Uncaught TypeError: this.series[0].update is not a function
The problem is that you sequentially remove the series from the chart, after each call the chart is redrawn and by the end of the for loop the chart doesn't have any series. When you do
this.series = [{
name: title,
colorByPoint: true,
data: pieSeries
}]
you are modifying the javascript object and therefore update method is not available when you try to do
this.series[0].update({
type: "pie"
});
because you are trying to call Highcharts method on a generic javascript object.
What you should do is
this.addSeries({
name: title,
colorByPoint: true,
data: pieSeries,
type: 'pie'
})
Also, a suggestion: pass argument false to remove method so that it it doesn't redraw every time. Just redraw when you add the new series.
So above call would look like
this.addSeries({
name: title,
colorByPoint: true,
data: pieSeries,
type: 'pie'
}, true)
1.
for(i=0;i<this.series.length;i++) {
this.series[i].remove();
}
The code above will not remove series items: see here
2.
The correct way to add series is:
this.addSeries({...});
3.
Final working code:
...
pieButton: {
text: 'pie',
onclick: function () {
var pieSeries = [];
$.each(category_totals, function(j, k) {
pieSeries.push( { name: j , y: k } );
});
while(this.series.length > 0) {
this.series[0].remove(true);
}
this.addSeries({
name: title,
colorByPoint: true,
data: pieSeries,
type: 'pie'
});
// As Rahul Sharma pointed out in comments above,
// you can pass the "type" option to
// addSeries method, making this call redundant
// this.series[0].update({
// type: "pie"
// });
}
}
...
I'm trying to display a new Highcharts. Usually I use data from local server and i'm able to load data this way:
data : <php echo $jsonEncoded['values']?>,
The problem is : I have to load data from a remote server and it doesn't work! I really don't understand why...
You will find below my code :
$.ajax({
url: 'myurl',
type: 'GET',
dataType : 'json',
success: function(json, statut){
data_day = json['day'];
data_values = json['js'];
data_start = json['start'];
options = {
chart: {
type: 'area',
renderTo: 'container_health',
},
titile: {
text: "text",
},
yAxis: {
title: {
text: 'Pourcentage'
},
max: 100,
},
series : [{
name: "test",
data: data_values,
pointStart: Data.UTC(data_start),
pointInterval: 24*3600*1000
},
]
};
chart = new Highcharts.Char(options);
}
Then I have 3 alerts:
alert(chart.series[0].pointInterval); //display well the date
alert(chart.series[0].data[0].y); //display undefined
alert(data_values); //display well values
So it seems, I don't have a problem when I want to access directly to a data from my JSON object (json['start']) but it seems it doesn't work when I try to access to my array from json['js']...
Is it a problem from Highcharts or the way to access to data?
EDIT :
All data don't work in options btw.
BR,
I use highcharts for draw charts. I have 2d json object and I don't know how to set this object to highcharts. And this is my json object data:
And I want my chart like this picture(column-parsed example of highchart):
And this is my code:
$.ajax({
url:"../../teachersem",
type:"get",
data:{
id:$.trim(tableData[0])
},
success:function(data){
$('div[class|="col-md-7 col-md-offset-3"]').css("display","none");
//console.log(data.accept);
//console.log(data.fail);
var accept=new Array();
var fail =new Array();
for (i = 0; i < data.accept.length; i++){
accept.push([data.accept[i].year, parseInt(data.accept[i].count)]);
alert("accept: "+data.accept[i].year+" "+parseInt(data.accept[i].count));
}
//console.log(accept.toString());
for (i = 0; i < data.fail.length; i++){
fail.push([data.fail[i].year, parseInt(data.fail[i].count)]);
alert("fail: "+data.fail[i].year+" "+parseInt(data.fail[i].count));
}
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "Student data"
},
xAxis: {
allowDecimals: false,
title: {
text: "Branch of studies"
}
},
yAxis: {
title: {
text: "Number of students"
}
},
series: [{
data: [accept,fail]
}],
});
},
error:
alert('error!')
})
});
But this has any result? please help,thank u!
You actually want two series: data parameters (one for each column).
The first column will be the accept data and the second column will be your fail data since I am guessing that your category label which in the example image is Apples will be a Branch of Studies.
Your series should look something similar to the following:
series: [{
name: "Accept",
data: accept,
},
{
name: "Fail",
data: fail,
}]
Your accept and fail arrays are currently arrays of arrays, but they can actually be a simple list as seen in the Highcharts demo here. You can then specify in the xAxis parameter the categories: that are your Branch of Studies.
I'm using CI (+HMVC) for showing a Highcharts with an ajax event on a form.
My pb is to create valids Series for the chart. I have to create 6 series from mysql DB. My chart code is inpired by
blank page highchart in using jquery to call json arrary.
My View
(<?=$instance_graph?> is everywhere because I want to be able to instance multiple charts)
$(document).ready(function() {
$('#submit<?=$instance_graph?>').click(function() {
$('#rendu_graph<?=$instance_graph?>').html('');
var form_data = {
from : $('#from[name=from<?=$instance_graph?>]').val(),
to : $('#to[name=to<?=$instance_graph?>]').val(),
parametre : $('#parametre[name=parametres<?=$instance_graph?>]').val(),
ajax : '1'
};
$.ajax({
url: "<?= site_url('graph_meteo/ajax_graph'); ?>",
type: 'POST',
async : false,
data: form_data,
dataType:'json',
success: function(data) {
//alert(msg) ;
//$('#rendu_graph<?=$instance_graph?>').html(msg);
var chartSeriesData=[];
$.each(data, function(i,item){
var series_name = item.name;
var series_data = item.data;
var series = {data: item.data,name:series_name};
chartSeriesData.push(series);
});
console.log(chartSeriesData) ;
chart = new Highcharts.Chart({ //Début du Highchar
chart: {
renderTo: 'rendu_graph<?=$instance_graph?>',
type: 'spline'
},
title: {
text: 'Graph'
},
subtitle: {
text: 'Title'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'param 1'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%a %d %b %H:%M', this.x) + ': ' + this.y + ' m';
}
},
series: chartSeriesData
})
The console.log of the series created :
[Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,30),63.425]", name="Station 1"}.
And of course I have one serie for each object with no plot:
edit :I'm looking for a way to have a nice working graph with these data ( 1 lines) and I want my code working for many lines/series. My big pb is to start from Query result to chart series format. An example could be nice answer.
I hope you could help me before I became mad!
First problem with your setup is that the data for each series is a string with an array in it. Currently it looks like:
{ data: "[Date.UTC(2013,02,06,14,15),65.09375]", name: "Station 1"}
The name looks ok, but the data should be a real javascript array, not a string. This is what you want it to look like:
{ data: [Date.UTC(2013,02,06,14,15),65.09375], name: "Station 1"}
When that is solved I think you should put all data-points in the same series-definition. So instead of:
{ data: [Date.UTC(2013,02,06,14,15),65.09375], name: "Station 1"},
{ data: [Date.UTC(2013,02,07,14,15),67.09375], name: "Station 1"}
You should have one series with many points:
{ data: [
[Date.UTC(2013,02,06,14,15),65.09375],
[Date.UTC(2013,02,07,14,15),67.09375],
<more data points here>],
name="Station 1"},