Populate JSON object to highchart bar chart - javascript

I am newbie parsing JSON object to highchart and I would like to plot basic bar graph.
I have done on the title of graph. The problem is that the series that I would like to show is not showing.(count as series and qpAnswer as xAxis).
Here is my JSON data
[
{
qpQuestion: "Is that a dog?",
qpAnswerId: "1",
qpAnswer: "Yes",
count: "0"
},
{
qpQuestion: "Is that a dog?",
qpAnswerId: "2",
qpAnswer: "No",
count: "0"
},
{
qpQuestion: "Is that a dog?",
qpAnswerId: "3",
qpAnswer: "ok",
count: "0"
}
]
Here is my JS
var url="sections.php?request=graph";
$.getJSON(url,function(data1){
var options={
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: data1[0].qpQuestion
},
xAxis:{
categories: data1.qpAnswer
title: {
text: 'Answer'
}
},
yAxis: {
min: 0,
title: {
text: 'Answer Count'
}
},
series:data1
};
var chart = new Highcharts.Chart(options);
});

You can pre-process the data to form like
var answers = ['Yes','No' ,'OK'];
var answer_counts= [
{name: 'Yes', data : [2,0,0]},
{name: 'No', data: [0,3,0]},
{name: 'OK', data: [0,0,1]} ];
Then plot it with
var options={
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text:'QA Answers'
},
xAxis:{
categories: answers,
title: {
text: 'Answer'
}
},
yAxis: {
min: 0,
title: {
text: 'Answer Count'
}
},
series:answer_counts
};
var chart = new Highcharts.Chart(options);
I have done in the fiddle, http://jsfiddle.net/gwC2V/1/
Let us know if it helps.

Below Example can help you
The JSON file
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
use getJSON() to retrive data from JSON file and Populate to CHART
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Here is link

Related

HighChart created before $.getJSON

I am using HighCharts to make a graph with columns, drilldown series and scatter. The problem which I am having, is that the HighChart is created before the $.getJSON function is succesfully exicited. I have found several other articles, but non yet where two $.getJSON functions are called. The code which I am using:
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container_genomefraction',
type: 'column',
events: {
// Declare the events changing when the drilldown is activated
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
},
title: {text : "Gbp"}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
// Declare the events changing when the drillup is activated
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
},
title: {text : "Percentages"}
}, false, false);
}
}
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: [{
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},{
min: 0,
title :{
text : 'input'
},
labels: {
format : '{value}'
},
opposite: true
}],
legend: {
enabled: false
},
plotOptions: {
series: {
marker: {
fillColor: '#FFFFFF',
lineWidth: 2,
lineColor: null, // inherit from series
size : 50
},
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
// Declare an empty series
series: [{
name: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
// Declare an empty drilldown series
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
// Your $.getJSON() request is now synchronous...
$.ajaxSetup({
async: false
});
// Get the input into one series
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
// Get the drilldown estimated and total size into one series
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
$.ajaxSetup({
async: true
});
});
My JSONs are formatted:
fraction.json
[{"name":"1","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3}]},{"name":"input","dataLabels":"{enabled,false}","yAxis":1,"type":"scatter","data":[{"y":38,"name":1,"drilldown":1},{"y":"","name":2,"drilldown":2},{"y":27,"name":3,"drilldown":3}],"tooltip":{"headerFormat":"<span style='font-size:11px'>{series.name}<\/span><br>","pointFormat":"<span style='color:{point.color}'>{point.name}<\/span>: <b>{point.y}<\/b><br\/>"}}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]}]
When the page is loaded, the graph displays the values of the previous search done and when I reload the page, the correct data is shown. Could someone please help me out?
Add the second getJSON method in the first getJSON success callback like this:
//Get the genome fraction into one series
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
//Get the drilldown estimated and total genome size into one series
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});

Change chart subtitle programmatically

Maybe not the best title, but what I'm trying to do is change the subtitle of my chart to include the last temperature displayed in it. Something like this
Last value: 4 degrees
The chart's data is in a csv file.
$(document).ready(function () {
var lastVal = 0;
$.get('csv/Temp.csv', function (csv) {
$('#Temp').highcharts({
chart: {
type: 'spline',
zoomType: 'xy'
},
data: {
csv: csv
},
title: {
text: 'Outside Temperature'
},
subtitle: {
text: 'Last value: '
},
yAxis: {
title: {
text: 'Units'
}
}
});
});
});
If I change the subtitle to:
subtitle: {
text: function () {
lastVal = this.yData[this.yData.length - 1];
return 'Last Value: ' + lastVal;
}
},
I only get the text. How do I do this?
You can change the chart subtitle programmatically using the function (API):
chart.setTitle(Object title, object subtitle, Boolean redraw)
An example would be:
chart.setTitle(null, { text: "New subtitle" }, true);
If you want this to happen on load with data from CSV, you could do it like this (JSFiddle):
chart: {
events: {
load: function(event) {
var lastValue = this.series[0].data[this.series[0].data.length-1].y;
this.setTitle(null,{ text: 'Last y-value: '+lastValue }, true);
}
}
}

Setting datasource of Kendo UI chart as well as showing the summary?

I am using ajax api calls for getting data from a SQL database as below:
function getJsonData(type, period1, period2, id) {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
url: createURL(type, period1, period2, id),
dataType: "json",
contentType: "application/json; chartset=utf-8"
}
},
});
return dataSource;
}
Using the above datasource, I am creating a Kendo chart as below:
function stepsChart(container, title, period1, period2) {
var dSource = getJsonData("Summary", period1, period2, "<% = id %>");
$(container).kendoChart({
dataSource: dSource,
seriesColors: ["orangered"],
chartArea: {
background: ""
},
title: {
text:title
},
legend: {
visible: false
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "column",
gap:5
},
series: [{
name: "steps",
field: "steps",
categoryField: "createddate",
aggregate: "sum"
}],
categoryAxis: {
type: "date",
baseUnit: getBaseUnit(period1, period2),
labels: {
rotation: -45,
dateFormats: {
days : getDateFormat(period1, period2),
weeks: getDateFormat(period1, period2),
years: getDateFormat(period1, period2)
},
step: getSteps(period1, period2)
},
majorGridLines: {
visible: false
}
},
valueAxis: {
majorGridLines: {
visible: true
},
labels: {
template: "#= kendo.format('{0}',value/1000)#K"
},
title: {
text: "Steps"
}
}
});
}
I also want to use the data from the above datasource for showing a summary of the information in a div below the chart. But if I add something like
var k = dSource.data;
there will not be any data in k. Is there a way to get the json data in the function which creates the chart?
DataSource.data is a function. I think your code should be:
var k = dSource.data();
That would also return an empty array if the data hasn't already been read, so you might need to do:
dSource.one("change", function () {
var k = dSource.data();
});
dSource.fetch();
because the .fetch() is async.

Split JSON into Multiple Array Series Highcharts

i get my JSON object from my php code in this format (JSONlint ok) :
[
[1375653600000,3.20104,175.00,116.00,11.00,31.00],[...],[1376776800000,2.85625,10.00,1.00,0.00,8.00]
]
i Have to split in 5 different series:
[1375653600000, 3.201014]
[1375653600000, 175.00]
[1375653600000, 116.00]
[1375653600000, 11.00]
[1375653600000, 31.00]
...
and (obviously) each array is for a different highcharts series.
i follow this post to get an idea about split the JSON:
Retrieving JSON data for Highcharts with multiple series?
This is my code:
$(function() {
// See source code from the JSONP handler at https://github.com/highslide-software/highcharts.com/blob/master/samples/data/from-sql.php
$.getJSON('grafico_nuovo.php?callback=?', function(data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2012, 9, 14, 19, 59), null, null, null, null]]);
// create the chart
$('#container').highcharts('StockChart', {
chart : {
type: 'spline',
zoomType: 'xy'
},
navigator : {
adaptToUpdatedData: false,
series : {
data : data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'analisi consumi e temperature'
},
subtitle: {
text: 'Analisi test solo temperatura media'
},
rangeSelector : {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 2,
text: '2d'
}, {
type: 'week',
count: 1,
text: '1w'
},{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true, // it supports only days
selected : 2 // day
},
/*xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},*/
xAxis: {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000, // one hour
type: 'datetime',
dateTimeLabelFormats: { minute: '%H:%M', day: '%A. %e/%m' },
// minRange: 15*60*1000,
//maxZoom: 48 * 3600 * 1000,
labels: {
rotation: 330,
y:20,
staggerLines: 1 }
},
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
},
{
name: 'val3',
data: []
},
{
name: 'val4',
data: []
},
{
name: 'val5',
data: []
}]
});
});
});
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var currentExtremes = this.getExtremes(),
range = e.max - e.min,
chart = $('#container').highcharts();
chart.showLoading('Loading data from server...');
$.getJSON('grafico_nuovo.php?start='+ Math.round(e.min) +
'&end='+ Math.round(e.max) +'&callback=?', function(data) {
val1 = [];
val2 = [];
val3 = [];
val4 = [];
val5 = [];
$.each(data, function(key,value) {
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
val3.push([value[0], value[3]]);
val4.push([value[0], value[4]]);
val5.push([value[0], value[5]]);
});
console.log('val1');
chart.series[0].setData(val1);
chart.series[1].setData(val2);
chart.series[2].setData(val3);
chart.series[3].setData(val4);
chart.series[4].setData(val5);
chart.hideLoading();
});
}
The navigator works fine (with little trouble after 3-4 clicks) but the other series doesn't show.
Everything should be ok, but i've probably missed something

How to set variable as categories in Highcharts

I have a variable
var country = ['Africa', 'America', 'Asia', 'Europe', 'Oceania'];
I want to set the categories of my chart into variable country. Please help..
I am new to Highcharts. Thanks
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'column'
},
title: {
text: 'Compliance Tracker '
},
xAxis: {
categories:
You can simply put it like this :
var country = ['Africa', 'America', 'Asia', 'Europe', 'Oceania'];
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: country,
title: {
text: null
}
}....
......
});
Here is the working fiddle : http://jsfiddle.net/3gGYK/
I hope, you want to know the same.

Categories

Resources